将图片转换成二进制

package com.example.rabbitmq.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

@RestController
public class Base64StringToImage {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public static BASE64Encoder encoder = new sun.misc.BASE64Encoder();
    public static BASE64Decoder decoder = new sun.misc.BASE64Decoder();

    //将图片转换成二进制
    @RequestMapping(value="/getimagebinary",produces = "text/plain;charset=UTF-8")
    public  String getImageBinary(){
        File file = new File("C:\\图片\\1.jpg");
        BufferedImage buff;
        try {
            buff = ImageIO.read(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ImageIO.write(buff, "jpg", bos);
            byte[] bytes = bos.toByteArray();
            base64StringToImage(encoder.encodeBuffer(bytes).trim());
        } catch (IOException e){
            logger.error("转换成二进制失败" + e.getMessage());
        }
        return "失败";
    }

    //将图片转换成二进制
    //@PostMapping(value="/base64stringtoimage",produces = "text/plain;charset=UTF-8")
    public  String base64StringToImage(@RequestParam("str") String str){
        try {
            byte[] bytes1 = decoder.decodeBuffer(str);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            BufferedImage bi1 = ImageIO.read(bais);
            File w2 = new File("C:\\图片\\4.jpg");
            ImageIO.write(bi1, "jpg", w2);
        } catch (IOException e) {
            logger.error("图片转换失败" + e.getMessage());
        }
        return "ok";
    }
}

你可能感兴趣的:(io,java)