gpt4 book ai didi

android - 无法使用 Volley 从 Json 响应保存图像

转载 作者:行者123 更新时间:2023-12-02 16:23:07 26 4
gpt4 key购买 nike

在 Android 中从 ImageView 保存图像不起作用。通过 Volley 从 JSON 加载图像。我想将该图像保存在图库中,但在某些设备上此代码不起作用。

BitmapDrawable draw = (BitmapDrawable) thumbnail.getDrawable();
Bitmap bitmap = draw.getBitmap();

FileOutputStream outStream = null;

File dir = new File(Environment.getExternalStorageDirectory() + "");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
try {
outStream.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(JobsDetail.this, "Download Successfully", Toas.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(dir));
sendBroadcast(intent);

最佳答案

只需使用它直接从图像网址下载

// DownloadImage AsyncTask
private class DownloadImage extends AsyncTask<String, Void, Bitmap> {

@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);

}

@Override
protected Bitmap doInBackground(String... URL) {

String imageURL = URL[0];

Bitmap bitmap = null;
try {
// Download Image from URL
InputStream input = new java.net.URL(imageURL).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}

@Override
protected void onPostExecute(Bitmap result) {

if (result != null) {
progressBar.setVisibility(View.GONE);

File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();

FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
LicenseFrontFile = destination;
} catch (IOException e) {
e.printStackTrace();
}
}
}

// Set the bitmap into ImageView

//image.setImageBitmap(result);
// Close progressdialog

}

要使用,请这样调用

new DownloadImage().execute(image_url);

还在 list 中添加写入权限

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

以及 Marshmallow 或以上设备的运行时权限

关于android - 无法使用 Volley 从 Json 响应保存图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49606842/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com