首先,您需要获取您的位图。您可以已经将其作为对象 Bitmap,也可以尝试从 ImageView 中获取它,例如:
BitmapDrawable drawable = (BitmapDrawable) mImageView1.getDrawable();
Bitmap bitmap = drawable.getBitmap();
然后您必须从 SD 卡中获取目录(File 对象),例如:
File sdCardDirectory = Environment.getExternalStorageDirectory();
接下来,创建用于图像存储的特定文件:
File image = new File(sdCardDirectory, "test.png");
之后,您只需要编写Bitmap,这要归功于它的方法compress,例如:
boolean success = false;
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
最后,如果需要,只需处理布尔结果。如:
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
不要忘记在您的清单中添加以下权限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>