图片并转换为Blob
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/55b85072c75946cd9bff1a28344df1d1.png)
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;
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
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();
}