如何在按钮上将图像保存到 SD 卡 单击 android [英] How to save the image to SD card on button Click android
问题描述
我在 1 XML 中使用 Imageview 和 Button,并且我正在从 webServer 检索图像作为 URL 并将其显示在 ImageView 上.现在,如果单击按钮(保存),我需要将该特定图像保存到 SD 卡中.如何做到这一点?
I am using an Imageview and a Button in 1 XML, and I am retriving the images as URL from webServer and displaying it on the ImageView. Now if the Button(Save) is clicked I need to save that particular image into SD card. How to do this?
注意:应保存当前图像.
NOTE: Present Image Should be saved.
推荐答案
首先,您需要获取 Bitmap.你可以已经将它作为一个对象 Bitmap,或者你可以尝试从 ImageView 中获取它,例如:
First, you need to get your Bitmap. You can already have it as an object Bitmap, or you can try to get it from the ImageView such as:
BitmapDrawable drawable = (BitmapDrawable) mImageView1.getDrawable();
Bitmap bitmap = drawable.getBitmap();
然后您必须从SD卡如:
Then you must get to directory (a File object) from SD Card such as:
File sdCardDirectory = Environment.getExternalStorageDirectory();
接下来,创建用于图像存储的特定文件:
Next, create your specific file for image storage:
File image = new File(sdCardDirectory, "test.png");
之后,您只需要编写位图,这要归功于它的方法 compress 如:
After that, you just have to write the Bitmap thanks to its method compress such as:
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();
}
最后,如果需要,只需处理布尔结果.如:
Finally, just deal with the boolean result if needed. Such as:
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();
}
不要忘记在您的清单中添加以下权限:
Don't forget to add the following permission in your Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
这篇关于如何在按钮上将图像保存到 SD 卡 单击 android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!