网络图片,内部存储图片保存到本地外部存储(可被相册和其他应用读取)

本文介绍了一种在安卓设备上从网络获取图片并将其保存至本地的方法。包括将已展示的图片保存到外部存储以及将内部存储的图片转移到外部存储以便于在相册中查看或供其他应用程序使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网络图片保存,拉取网络图片后展示,保存到本地外部存储(前提是图片已展示),lin_qrcode是图片容器,或父容器,父父容器

Bitmap bitmap = BitmapUtil.getCacheBitmapFromView(lin_qrcode);
if (bitmap != null) {
    boolean result = SimpleUtils.saveBitmapToLocation(bitmap);
    bitmap.recycle();
    if (result) FunCom.showToast(getString(R.string.save_success));
}

内部存储图片,保存到本地外部存储(内部存储图片,即包名文件夹内的图片,无法被外部访问,需要保存到外部,在相册查看或其他应用获取),localUri为图片Uri

try {
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), localUri);
    if (bitmap != null) {
        boolean result = SimpleUtils.saveBitmapToLocation(bitmap);
        bitmap.recycle();
        if (result) FunCom.showToast(context.getString(R.string.save_success));
    }
} catch (IOException e) {
    e.printStackTrace();
}

所用工具类

public static boolean saveBitmapToLocation(Bitmap bm) {
    try {
        File basePath = FileHelper.getBasePath();

        Calendar now = new GregorianCalendar();
        SimpleDateFormat simpleDate = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
        String fileName = simpleDate.format(now.getTime()) + ".jpg";

        File file = new File(basePath, fileName);

        FileOutputStream fos = new FileOutputStream(file);
        bm.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
        fos.close();

        Uri uri = Uri.fromFile(file);
        RedBeanApplication.getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
    return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值