我设置使用的ImageView setImageBitmap
与外部图像的URL。 我想保存图像,以便它可以在以后即使没有互联网连接使用。 在哪里以及如何保存呢?
Answer 1:
你必须将它保存在SD卡或在您的包数据,因为在运行时,你只能访问这些。 要做到这一点,这是一个很好的例子
URL url = new URL ("file://some/path/anImage.png");
InputStream input = url.openStream();
try {
//The sdcard directory e.g. '/sdcard' can be used directly, or
//more safely abstracted with getExternalStorageDirectory()
File storagePath = Environment.getExternalStorageDirectory();
OutputStream output = new FileOutputStream (storagePath + "/myImage.png");
try {
byte[] buffer = new byte[aReasonableSize];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
output.write(buffer, 0, bytesRead);
}
} finally {
output.close();
}
} finally {
input.close();
}
来源: 如何将图像从它的URL转移到SD卡?
Answer 2:
URL imageurl = new URL("http://mysite.com/me.jpg");
Bitmap bitmap = BitmapFactory.decodeStream(imageurl.openConnection().getInputStream());
此代码将帮助您从图像生成URL的位图。
这个问题回答的第二部分。
Answer 3:
你可以保存图像中的SD卡,你可以使用图像中的未来没有互联网。
请参阅本教程将介绍如何存储图像,然后再次读取。
希望对你有帮助.....!
Answer 4:
可能是它会帮助别人像我一天
new SaveImage().execute(mViewPager.getCurrentItem());//calling function
private void saveImage(int currentItem) {
String stringUrl = Site.BASE_URL + "socialengine/" + allImages.get(currentItem).getMaster();
Utils.debugger(TAG, stringUrl);
HttpURLConnection urlConnection = null;
try {
URL url = new URL(stringUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
File sdCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
String fileName = stringUrl.substring(stringUrl.lastIndexOf('/') + 1, stringUrl.length());
String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
File imgFile = new File(sdCardRoot, "IMG" + System.currentTimeMillis() / 100 + fileName);
if (!sdCardRoot.exists()) {
imgFile.createNewFile();
}
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
FileOutputStream outPut = new FileOutputStream(imgFile);
int downloadedSize = 0;
byte[] buffer = new byte[2024];
int bufferLength = 0;
while ((bufferLength = inputStream.read(buffer)) > 0) {
outPut.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
Utils.debugger("Progress:", "downloadedSize:" + Math.abs(downloadedSize*100/totalSize));
}
outPut.close();
//if (downloadedSize == totalSize);
//Toast.makeText(context, "Downloaded" + imgFile.getPath(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
private class SaveImage extends AsyncTask<Integer, Void, String> {
@Override
protected String doInBackground(Integer... strings) {
saveImage(strings[0]);
return "saved";
}
@Override
protected void onPostExecute(String s) {
Toast.makeText(context, "" + s, Toast.LENGTH_SHORT).show();
}
}
文章来源: How can I save an image from a url?