首先,您需要获取位图。您已经可以将其作为对象位图,或者您可以尝试从 ImageView 获取它,例如:
BitmapDrawable drawable = (BitmapDrawable) mImageView1.getDrawable();
Bitmap bitmap = drawable.getBitmap();
然后你必须进入目录(aFile http://developer.android.com/reference/java/io/File.html来自 SD 卡的对象),例如:
File sdCardDirectory = Environment.getExternalStorageDirectory();
接下来,创建用于图像存储的特定文件:
File image = new File(sdCardDirectory, "test.png");
之后,您只需通过其方法编写位图即可compress http://developer.android.com/reference/android/graphics/Bitmap.html#compress%28android.graphics.Bitmap.CompressFormat,%20int,%20java.io.OutputStream%29例如:
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"/>