如何在android中下载图像?
How to download image in android?
我右边有一张图片,左边有一个按钮 "download"。该图像来自我的可绘制对象。现在,当我尝试单击下载时,我想将图像放到我的 SD 卡下载中。请帮助我,我只在 url 中看到有关下载的信息。有没有其他解决方案。谢谢
public class ImageDownloader {
public void download(String url, ImageView imageView) {
BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
task.execute(url);
}
}
/* class BitmapDownloaderTask, see below */
}
首先,您需要获取位图。你可以已经将它作为一个对象 Bitmap,或者你可以尝试从 ImageView
中获取它,例如:
BitmapDrawable drawable = (BitmapDrawable) ImageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
然后你必须从 SD 卡获取目录(一个文件对象),例如:
File sdCardDirectory = Environment.getExternalStorageDirectory();
接下来,创建用于图像存储的特定文件:
File image = new File(sdCardDirectory, "test.png");
之后,您只需编写位图,例如:
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"/>
我右边有一张图片,左边有一个按钮 "download"。该图像来自我的可绘制对象。现在,当我尝试单击下载时,我想将图像放到我的 SD 卡下载中。请帮助我,我只在 url 中看到有关下载的信息。有没有其他解决方案。谢谢
public class ImageDownloader {
public void download(String url, ImageView imageView) {
BitmapDownloaderTask task = new BitmapDownloaderTask(imageView);
task.execute(url);
}
}
/* class BitmapDownloaderTask, see below */
}
首先,您需要获取位图。你可以已经将它作为一个对象 Bitmap,或者你可以尝试从 ImageView
中获取它,例如:
BitmapDrawable drawable = (BitmapDrawable) ImageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
然后你必须从 SD 卡获取目录(一个文件对象),例如:
File sdCardDirectory = Environment.getExternalStorageDirectory();
接下来,创建用于图像存储的特定文件:
File image = new File(sdCardDirectory, "test.png");
之后,您只需编写位图,例如:
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"/>