如何下载图像并将其保存在Android图库
问题描述:
我得到的图像链接从服务器和它应该下载并保存到库中的链接点击,我对如何做到这一点毫无头绪。请帮助我在此,先谢谢了。
I get image link from the server and on click of the link it should download and save it to the gallery, I have no clue on how to do it. please help me on this, thanks in advance
答
试试这个code,呼叫 mDownloadAndSave()
为节省SD卡图像的方法,它会解决你的问题。
Try this code, Call mDownloadAndSave()
method for save image on SDCard, it will solve your problem.
public void mDownloadAndSave() {
// Setting up file to write the image to.
File f = new File("/mnt/sdcard/img.png");
// Open InputStream to download the image.
InputStream is;
try {
is = new URL("http://www.tmonews.com/wp-content/uploads/2012/10/androidfigure.jpg").openStream();
// Set up OutputStream to write data into image file.
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
和不要忘了下面的权限加入到AndroidManifest.xml中
And Don't forget to add below permission into Androidmanifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>