从drawable把图片放入外部存储目录中

本文详细介绍如何在Android应用中从drawable目录读取图片资源,并将其复制到设备的Pictures目录下,同时提供了将图片路径转换为Bitmap对象的方法。

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

/**
     * 从drawable把图片放入data
     *
     * @return File
     * @param context
     * @param resId
     */

try {
            // path==/storage/emulated/0/Pictures

            File LogoFileRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            //Log.i("tag", "path==" + LogoFileRoot.getPath());
            // 计算图片存放全路径
            // String LogoFilePath = LogoFileRoot+"/"+"a.jpg";
            File dir = new File(LogoFileRoot.getPath());
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File file = null;
            // 如果文件夹不存在,创建一个(只能在应用包下面的目录,其他目录需要申请权限 OWL)
            if (dir.isDirectory()) {
                file = new File(dir.getPath() + dir.separator + "a.png");
            }

            // 获得封装 文件的InputStream对象
            is = context.getResources().openRawResource(resId);

            

            fos = new FileOutputStream(file);

            byte[] buffer = new byte[8192];
            
            int count = 0;

            // 开始复制Logo图片文件
            while ((count = is.read(buffer)) > 0) {
                fos.write(buffer, 0, count);
                
            }

            return file;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

/**
     * file.getPath()从data目录拿到bitmap对象
     * @param url
     * @return bitmap
     */
    public static Bitmap getBitmap(String url){
        
        try {
            //把图片文件打开为文件流,然后解码为bitmap
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (Exception e) {
            e.printStackTrace();
             return null;
        }
    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

转载于:https://my.oschina.net/juna/blog/688144

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值