java 图片并转换为Blob

发布于:2024-08-02 ⋅ 阅读:(143) ⋅ 点赞:(0)

图片并转换为Blob

在这里插入图片描述

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Blob;
import javax.sql.rowset.serial.SerialBlob;
/**
     * 图片并转换为Blob
     * @param imageUrl 图片链接
     * @return Blob
     * @throws Exception
     */
    public Blob downloadImageAndConvertToBlob(String imageUrl) throws Exception {
        String fileName = imageUrl.substring(imageUrl.lastIndexOf("/")+1);
        String destinationPath = "C:\\Users\\ASUS\\Desktop\\aa\\"+ fileName;
        try {
            downloadImagess(imageUrl, destinationPath);
            File file = new File(destinationPath);
            byte[] fileData = new byte[(int) file.length()];
            FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream.read(fileData);
            fileInputStream.close();
            // 将字节数组写入Blob对象
			return new SerialBlob(fileData);
        }catch (Exception e){
            log.error("图片下载失败!");
        }
        return null;
    }

```css
 /**
     * 下载图片
     * @param imageUrl 图片链接
     * @param destinationPath 下载地址
     * @throws IOException 输入输出异常
     */
    public static void downloadImagess(String imageUrl, String destinationPath) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        InputStream inputStream = connection.getInputStream();
        FileOutputStream outputStream = new FileOutputStream(destinationPath);
        byte[] buffer = new byte[2048];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        inputStream.close();
        outputStream.close();
        connection.disconnect();
    }


网站公告

今日签到

点亮在社区的每一天
去签到