栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用MediaStore在Android Q中保存图像?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用MediaStore在Android Q中保存图像?

请尝试下一种方法。Android
Q已经负责创建文件夹(如果不存在)。该示例经过硬编码后可以输出到Pictures文件夹中。如果您需要一个子文件夹,请在下一个子文件夹名称后添加:

final String relativeLocation = Environment.DIRECTORY_PICTURES + File.separator + “YourSubforderName”;

考虑到压缩格式应与mime-type参数相关。例如,对于JPEG压缩格式,mime类型将为“ image / jpeg”,依此类推。

private void saveBitmap(@NonNull final Context context, @NonNull final Bitmap bitmap,  @NonNull final Bitmap.CompressFormat format, @NonNull final String mimeType,  @NonNull final String displayName) throws IOException{    final String relativeLocation = Environment.DIRECTORY_PICTURES;    final ContentValues  contentValues = new ContentValues();    contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, displayName);    contentValues.put(MediaStore.MediaColumns.MIME_TYPE, mimeType);    contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, relativeLocation);    final ContentResolver resolver = context.getContentResolver();    OutputStream stream = null;    Uri uri = null;    try    {        final Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;        uri = resolver.insert(contentUri, contentValues);        if (uri == null)        { throw new IOException("Failed to create new MediaStore record.");        }        stream = resolver.openOutputStream(uri);        if (stream == null)        { throw new IOException("Failed to get output stream.");        }        if (bitmap.compress(format, 95, stream) == false)        { throw new IOException("Failed to save bitmap.");        }    }    catch (IOException e)    {        if (uri != null)        { // Don't leave an orphan entry in the MediaStore resolver.delete(uri, null, null);        }        throw e;    }    finally    {        if (stream != null)        { stream.close();        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/452908.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号