我从服务器获取图像链接,点击它应下载的链接并将其保存到图库,我不知道如何做到这一点。请帮助我,提前谢谢
答案 0 :(得分:0)
**combine the below code to store image at a particula path**
File storagePath = new File(Environment
.getExternalStorageDirectory()
+ "/com.logistics.herestethiparty/images/");
storagePath.mkdirs();
File file = new File(storagePath, fileImageName);
**i have used the below code in asyncclass for image download**
URL url = new URL(imageUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
FileOutputStream fileOutput = new FileOutputStream(file);
InputStream inputStream = urlConnection.getInputStream();
int downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
}
// close the output stream when done
fileOutput.close();
答案 1 :(得分:0)
尝试使用此代码,调用mDownloadAndSave()
方法在SD卡上保存图像,它将解决您的问题。
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
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>