将 Android 中的位图另存为文件夹中外部存储中的 JPEG [英] Save Bitmap in Android as JPEG in External Storage in a folder

查看:18
本文介绍了将 Android 中的位图另存为文件夹中外部存储中的 JPEG的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用此代码将位图保存在外部存储中,但如果文件夹不存在,则不会创建该文件夹:

I am using this code to save Bitmap in External Storage but it does not create the folder if it not exists:

String path = Environment.getExternalStorageDirectory().toString();
        OutputStream fOutputStream = null;
        File file = new File(path + "/Captures/", "screen.jpg");
        try {
            fOutputStream = new FileOutputStream(file);

            capturedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);

            fOutputStream.flush();
            fOutputStream.close();

            MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
            return;
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Save Failed", Toast.LENGTH_SHORT).show();
            return;
        }

如果图像不存在,如何将图像保存在新目录中,如果文件夹在设备中,如何保存默认值?

How can I save the image in the new directory if not exists and save default if the folder is there in the device?

推荐答案

试试这个它肯定会给你结果:

try this it will gives u result sure:

String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/req_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);
Log.i(TAG, "" + file);
if (file.exists())
    file.delete();
try {
    FileOutputStream out = new FileOutputStream(file);
    bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
    out.flush();
    out.close();
} catch (Exception e) {
    e.printStackTrace();
}

将此添加到图库中:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));

查看此链接以获得明确的答案:在图库中显示文件夹图片

look at this link for clear answer: show folder images in gallery

这篇关于将 Android 中的位图另存为文件夹中外部存储中的 JPEG的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆