package com.huimv.manage.eartag.controller;

import com.huimv.manage.util.ImageUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;




import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
/**
 * @Project : huimv.shiwan
 * @Package : com.huimv.biosafety.uface.controller
 * @Description : TODO
 * @Version : 1.0
 * @Author : ZhuoNing
 * @Create : 2020-12-25
 **/
@SpringBootTest
public class Base64Test {
    private String imageURL = "D:/img/baidu.jpg";

    @Test
    public void testBase64Encoder(){
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            StringBuilder pictureBuffer = new StringBuilder();
            InputStream input = new FileInputStream(new File(imageURL));
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] temp = new byte[1024];
            for(int len = input.read(temp); len != -1;len = input.read(temp)){
                out.write(temp, 0, len);
                pictureBuffer.append(encoder.encode(out.toByteArray()));
                //out(pictureBuffer.toString());
                out.reset();
            }

            out(pictureBuffer.toString());
            out("Encoding the picture Success");

            BASE64Decoder decoder = new BASE64Decoder();
            FileOutputStream write = new FileOutputStream(new File("D:/img/test2.png"));
            byte[] decoderBytes = decoder.decodeBuffer(pictureBuffer.toString());
            write.write(decoderBytes);
            out("Decoding the picture Success");

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public void out(Object o){
        System.out.println(o.toString());
    }

    @Autowired
    private ImageUtils imageUtils;

    @Test
    public void toImg(){
        String base64 = "data:image/jpg;base64,[encoded data, 6324 characters]";
        String path = "D:\\img\\";
        String imgName = "test_baidu.jpg";
        //
        imageUtils.decodeBase64ToImage(base64,path,imgName);


    }
}
