下载图像后,我将其保存在的内部存储器中
Android/data/%packagename%/cache目录。下面是一个代码。
private class SaveImageToStorage extends AsyncTask<Void,Void,Void>
{
String picName;
Bitmap bitmap;
public SaveImageToStorage(String name, Bitmap bitmap)
{
this.picName = name;
this.bitmap = bitmap;
}
@Override
protected Void doInBackground(Void... params) {
if(bitmap != null && !picName.isEmpty()) {
File file = new File(feedImagesCacheDir.getPath(), extractImageNameFromUrl(picName));
try {
FileOutputStream fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.WEBP, 80, fos);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
在所有这些之后,我只想在android图库中打开图片。
我尝试了下面的代码,但它不起作用。它显示Toast"找不到图像"。
所以我试着删除了"file://",然后它打开了画廊,只留下了一些像破损的图像图标之类的东西。
private void openImageInGallery(){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://"+getFeedImagesCacheDir().getPath() + "/" + imgName+".webp"), "image/*");
startActivity(intent);
}
我想也许我把它保存在缓存文件夹中,所以它变成了私人的,只能访问我的应用程序。
我该怎么解决这个问题?
谢谢。很抱歉我的工程师不好。
缓存图像不能直接查看,因为它是像加密格式一样保存的,所以首先下载该图像并保存到SD卡中。使用以下代码。
String root = Environment.getExternalStorageDirectory().toString();
String wallpaperFilePath=Android/data/%packagename%/cache/imagename;
File cacheDir = GlobalClass.instance().getCacheFolder(this);
File cacheFile = new File(cacheDir, wallpaperFilePath);
InputStream fileInputStream = new FileInputStream(cacheFile);
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = scale;
bitmapOptions.inJustDecodeBounds = false;
Bitmap wallpaperBitmap = BitmapFactory.decodeStream(fileInputStream, null, bitmapOptions);
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
wallpaperBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
并将其添加到清单中
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
通过使用此行,您可以在图库视图中查看保存的图像。
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
您可以将图像下载到DCIM(您在sdCard中的图库文件夹)中。然后使用以下内容打开图库:
public static final int RESULT_GALLERY = 0;
Intent galleryIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );
如果你想获得结果URI或做任何其他事情,请使用这个:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case QuestionEntryView.RESULT_GALLERY :
if (null != data) {
imageUri = data.getData();
//Do whatever that you desire here. or leave this blank
}
break;
default:
break;
}
}
希望得到帮助!