package com.yuchen.saas.park.api.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;

/**
 * @ClassName ImageUrlToBase64Util
 * @Description TODO
 * @Author mqs
 * @Date 2024/10/31 14:43
 * @Version 1.0
 */
public class ImageUrlToBase64Util {

    public static String imageUrlToBase64(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");

        InputStream inputStream = new BufferedInputStream(connection.getInputStream());
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer))!= -1) {
            outputStream.write(buffer, 0, length);
        }

        byte[] imageBytes = outputStream.toByteArray();
        inputStream.close();
        outputStream.close();
        connection.disconnect();

        return Base64.getEncoder().encodeToString(imageBytes);
    }

    /*public static void main(String[] args) {
        String imageUrl = "https://prerelease.park.fj-yuchen.com/image/4d38d143-aa9c-4cf6-94b3-780d03969ef6.jpeg";
        try {
            String base64Image = imageUrlToBase64(imageUrl);
            System.out.println(base64Image);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/

}
