Android 如何从 url 保存图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10388666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I save an image from a url?
提问by Amit
I'm setting an ImageView using setImageBitmap
with an external image url. I would like to save the image so it can be used later on even if there is no internet connection. Where and how can I save it?
我正在使用setImageBitmap
外部图像 url设置 ImageView 。我想保存图像,以便以后即使没有互联网连接也可以使用。我在哪里以及如何保存它?
回答by coderplus
回答by Sarim Sidd
You have to save it in SD card or in your package data, because on runtime you only have access to these. To do that this is a good example
您必须将其保存在 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();
}
Source : How do I transfer an image from its URL to the SD card?
回答by Kishan Solanki
If you are using Kotlinand Glidein your app then this is for you:
如果您在您的应用中使用Kotlin和Glide,那么这适合您:
Glide.with(this)
.asBitmap()
.load(imageURL)
.into(object : SimpleTarget<Bitmap>(1920, 1080) {
override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap>?) {
saveImage(bitmap)
}
})
and this is that function
这就是那个功能
internal fun saveImage(image: Bitmap) {
val savedImagePath: String
val imageFileName = System.currentTimeMillis().toString() + ".jpg"
val storageDir = File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString() + "/Folder Name")
var success = true
if (!storageDir.exists()) {
success = storageDir.mkdirs()
}
if (success) {
val imageFile = File(storageDir, imageFileName)
savedImagePath = imageFile.absolutePath
try {
val fOut = FileOutputStream(imageFile)
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut)
fOut.close()
} catch (e: Exception) {
e.printStackTrace()
}
galleryAddPic(savedImagePath)
}
}
private fun galleryAddPic(imagePath: String) {
val mediaScanIntent = Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
val f = File(imagePath)
val contentUri = FileProvider.getUriForFile(applicationContext, packageName, f)
mediaScanIntent.data = contentUri
sendBroadcast(mediaScanIntent)
}
galleryAddPic()
is used to see the image in a phone gallery.
galleryAddPic()
用于查看手机图库中的图像。
Note:now if you face file uri exception then thiscan help you.
注意:现在如果您遇到文件 uri 异常,那么这可以帮助您。
回答by MAC
you can save image in sdcard and you can use that image in future without internet.
您可以将图像保存在 sdcard 中,以后可以在没有互联网的情况下使用该图像。
see this tutorialwill show how to store image and again read it.
请参阅本教程将展示如何存储图像并再次阅读它。
Hope this will help you.....!
希望能帮到你.....!
回答by Aklesh Singh
May be its will help someone like me one day
也许有一天它会帮助像我这样的人
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();
}
}