package com.ms.biz.tool;

import com.ms.biz.common.Ret;
import com.ms.biz.common.StrObjMap;

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

public class ImageTool {

    public static Ret getImageDataFromUrl(String imageUrl) {
        try {
            URL url = new URL(imageUrl);
            BufferedImage bufferedImage = ImageIO.read(url);

            String format = imageUrl.substring(imageUrl.lastIndexOf(".") + 1);
            if (!"bmp".equals(format) && !"png".equals(format) && !"jpg".equals(format) && !"jpeg".equals(format)) {
                format = "unknown";
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, format, baos);
            byte[] bytes = baos.toByteArray();

            Ret ret = CommonTool.successResult();
            StrObjMap data = new StrObjMap();
            data.put("imageData", bytes);
            data.put("imageType", "image/" + format);
            ret.setData(data);

            return ret;
        } catch (IOException e) {
            e.printStackTrace();
            return CommonTool.failResult();
        }
    }


    public static byte[] convertBmpToJpgDataByImgData(byte[] bmpData) throws IOException {
        BufferedImage bmpImage = ImageIO.read(new ByteArrayInputStream(bmpData));
        ByteArrayOutputStream jpgOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bmpImage, "jpg", jpgOutputStream);

        return jpgOutputStream.toByteArray();
    }

}
