zoukankan      html  css  js  c++  java
  • 图片和Base64之间的转换

    需求:保存h5页面图片至相册

    分析:

    1.获取h5返回的base64码。

    2.将base64码转换为Bitmap图片。

    3.新建文件,将图片存储至指定路径。

    4.通知相册更新。

    1.图片-base64解码工具类如下。

    注意:base64转成Bitmap时,需要去除所有"/r/n"、"data:image/png;base64,"字符,否则会造成解码失败,Bitmap为空的情况。

    public class TypeConverter {
    
        //图片转化成base64字符串
        public static String imageEncode(String path) {
    
            //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
            InputStream in = null;
            byte[] data = null;
            //读取图片字节数组
            try {
                in = new FileInputStream(new File(path));
                data = new byte[in.available()];
                in.read(data);
                in.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            //对字节数组Base64编码
            return Base64.encodeToString(data, Base64.DEFAULT);//返回Base64编码过的字节数组字符串
        }
    
    
    
        //base64字符串转化成图片
        public static String imageDecode(Context context, String imgStr,String imagePath,String imageName) {
            imgStr = imgStr.replaceAll("/r/ndata:image/png;base64,","");
    
            //对字节数组字符串进行Base64解码并生成图片
            if (imgStr == null) //图像数据为空
                return "";
    
            //Base64解码
            byte[] b = Base64.decode(imgStr,Base64.DEFAULT);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            //生成jpeg图片
    //        String imgFilePath = context.getExternalCacheDir().getPath()+"/hema_card.jpg";//新生成的图片
            String imgFilePath = imagePath+"/"+imageName;//新生成的图片
            LogUtils.e("生成的图片地址为:"+imgFilePath);
            OutputStream out = null;
            try {
                out = new FileOutputStream(imgFilePath);
                out.write(b);
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        imagePath, imageName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+imgFilePath)));
            return imgFilePath;
        }
    
        /**
         * bitmap转为base64
         * @param bitmap
         * @return
         */
        public static String bitmapToBase64(Bitmap bitmap) {
    
            String result = null;
            ByteArrayOutputStream baos = null;
            try {
                if (bitmap != null) {
                    baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    
                    baos.flush();
                    baos.close();
    
                    byte[] bitmapBytes = baos.toByteArray();
                    result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (baos != null) {
                        baos.flush();
                        baos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    
        /**
         * base64转为bitmap
         * @param base64Data
         * @return
         */
        public static Bitmap base64ToBitmap(String base64Data) {
            base64Data = base64Data.replace("data:image/png;base64,","");
            byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
        }
    }

    2.存储文件至指定路径。

     2.1.添加存储权限。 

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    2.2.保存图片,并通知相册刷新。

     public static void saveImageToGallery(Context context, Bitmap bitmap, String fileName,String toast){
            // 首先保存图片
            File file = new File(Environment.getExternalStorageDirectory().getPath()+"/"+fileName);//log: storage/emulated/0/hema2.jpg
    
            try {
                if(!file.exists()){
                    file.createNewFile();
                }
                FileOutputStream fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
                if(!TextUtils.isEmpty(toast)){
                    ToastUtils.showToast(toast);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        file.getAbsolutePath(), fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+file.getPath())));
        }

    参考博客:

    1.https://blog.csdn.net/chunlongyuan/article/details/7696070

    2.https://blog.csdn.net/wolfking0608/article/details/79289799#commentBox

  • 相关阅读:
    项目成本管理(三)
    项目成本管理(二)
    项目成本管理(一)
    男士香水
    荷兰猛兽-梅尔文训练体能
    PP学习笔记-业务基础
    SAP入行就业
    PP学习笔记02
    BZOJ 3012: [Usaco2012 Dec]First! 字典树 + tarjan
    CF319E Ping-Pong 线段树 + vector + 思维
  • 原文地址:https://www.cnblogs.com/fangg/p/10735085.html
Copyright © 2011-2022 走看看