问题
I have tried to implement undo and redo feature in android fingerpaint app. I have tried to implement using the below code.
Error
03-26 20:42:12.020: W/System.err(28056): java.lang.NullPointerException
03-26 20:42:12.020: W/System.err(28056): at baked.soft.FirstActivity.toJPEGFile(FirstActivity.java:341)
03-26 20:42:12.020: W/System.err(28056): at baked.soft.FirstActivity.onOptionsItemSelected(FirstActivity.java:314)
FirstActivity
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.tools:
ll.setVisibility(LinearLayout.VISIBLE);
return true;
case R.id.import_pics:
getPhotos();
return true;
case R.id.save:
toJPEGFile();
return true;
case R.id.trash:
trash();
return true;
}
return false;
}
private void toJPEGFile() {
// TODO Auto-generated method stub
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); // ERROR 341 LINE
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I don't know where is wrong. please help me. Thanks in advance!
回答1:
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
as you point out is the error line.
finalBitmap has not been initialised.
Aka, it is not a bitmap, it is a null value. Make sure you load your bitmap into this variable first.
finalBitmap = .... // assign finalBitmap.
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); // Then save to file
Edit:
reading from your comment, one way to do it would be to do the following, in onDraw method:
canvas.drawBitmap(bitmap, 0, 0, paint);
finalBitmap = bitmap;
But again, ive no idea where you are getting bitmap from. Is this another global variable? Maybe you could just change finalBitmap.compress... to bitmap.compress...
来源:https://stackoverflow.com/questions/15645048/save-bitmap-to-file