Android-读取本地文本,把Base64 datastring转换为图片

本文介绍了一种将图片文件转换为Base64编码字符串,并将其保存到外部存储设备的方法。通过使用Java的Bitmap和Base64编码库,实现了图片的高效编码与存储。

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

         String path="storage/sdcard0/a.jpg";
         Bitmap b= BitmapFactory.decodeFile(path);
         ByteArrayOutputStream out = null;
         try {
             out = new ByteArrayOutputStream();
                 b.compress(Bitmap.CompressFormat.JPEG, 100, out);
             out.flush();
             out.close();
             byte[] imgBytes = out.toByteArray();
             String b64=Base64.encodeToString(imgBytes, Base64.CRLF);
         System.out.println(b64);
         RandomAccessFile raf = new RandomAccessFile(mFile, "rw");
         raf.seek(mFile.length());
         raf.write(b64.getBytes());
         raf.close();
         } catch (Exception e) {
         // TODO Auto-generated catch block

         } finally {
         try {
         out.flush();
         out.close();
         } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
         }
         }
----------------------------------------------------------------------------
 String  sdPath=Environment.getExternalStorageDirectory().toString();

        StringBuffer sb = new StringBuffer();
        File file = new File(sdPath+"/base64.txt");
        try {
            FileInputStream fis = new FileInputStream(file);
            int c;
            while ((c = fis.read()) != -1) {
                sb.append((char) c);
            }
            fis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //--------------------转换分割线-------------------------------------
        byte[] bytes = Base64.decode(sb.toString(), Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);

        File newFile = new File(sdPath, "new.jpg");
        if (!newFile.exists()) {
            try {
                newFile.createNewFile();
                FileOutputStream o = new FileOutputStream(newFile);
                if (bitmap.compress(Bitmap.CompressFormat.JPEG, 100, o)) {
                    Toast.makeText(this, "转换成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "转换失败", Toast.LENGTH_SHORT).show();
                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值