【JAVA】图片与BASE64互相转换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sdut406/article/details/84846048
在项目中用到了图片转base64,以前没碰到过,所以在这里做个记录。

BASE64转图片

主要就是把图片转换成字节,当然你也可以通过new String(bytes,“UTF-8”); 获取字符串

 public static boolean base64ToImg(String imgbase64, String imgPath){
        if (imgbase64 == null){
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] bytes = null;
        try(OutputStream out = new FileOutputStream(imgPath)){
            bytes = decoder.decodeBuffer(imgbase64);
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] < 0){
                    bytes[i] += 256;
                }
            }
            out.write(bytes);
            out.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

图片转BASE64

 public static boolean  imgToBase64(File file,String filePath) {
        if (file.isDirectory()) {
            System.out.println("这是文件夹" + file.getAbsolutePath());
            return false;
        } else if (file.isFile()) {
            String fileName = file.getName();
            System.out.println("-----开始处理文件----" + fileName);
            FileWriter fileWriter = null;
            byte[] bytes = null;
            BASE64Encoder encoder = new BASE64Encoder();
            try (InputStream inputStream = new FileInputStream(file)) {
                // available 获取本地文件大小
                bytes = new byte[inputStream.available()];
                inputStream.read(bytes);
                String imgdata = encoder.encode(bytes);
                File file3 = new File(filePath);
                //  创建新文件
                if (!file3.exists()) {
                    file3.createNewFile();
                }
                fileWriter = new FileWriter(file3.getAbsoluteFile(), true);
                fileWriter.write(imgdata);
                fileWriter.close();
                return true;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }else {
            System.out.println("未知的文件");
            return false;
        }
    }

这个还是很简单的,我这里是输入的文件中去,所以需要注意流的关闭!主要就是利用了BASE64EncoderBASE64Decoder,没有太深的技术含量
DEMO资源地址

猜你喜欢

转载自blog.csdn.net/sdut406/article/details/84846048