java 通过图片地址 转换图片信息 小于4mb 分辨率不高于4096x4096 如果不符合转化为符合条件的图片 存在MultipartFile
时间: 2024-01-23 08:33:52 浏览: 103
java转换图片
您好!可以使用Java的ImageIO类来读取图片信息,以下是一个简单的代码示例:
```java
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class ImageUtils {
public static BufferedImage readImage(String imagePath) throws IOException {
URL url = new URL(imagePath);
BufferedImage image = ImageIO.read(url);
if (image == null) {
throw new IOException("Failed to read image from " + imagePath);
}
return image;
}
public static BufferedImage resizeImage(BufferedImage originalImage, int targetWidth, int targetHeight) {
int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizedImage = new BufferedImage(targetWidth, targetHeight, type);
resizedImage.getGraphics().drawImage(originalImage, 0, 0, targetWidth, targetHeight, null);
return resizedImage;
}
public static byte[] toByteArray(BufferedImage image, String format) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, format, baos);
return baos.toByteArray();
}
public static void main(String[] args) throws IOException {
String imagePath = "https://example.com/image.jpg";
BufferedImage originalImage = readImage(imagePath);
int width = originalImage.getWidth();
int height = originalImage.getHeight();
if (width > 4096 || height > 4096 || toByteArray(originalImage, "jpg").length > 4 * 1024 * 1024) {
// image does not meet the requirements, resize it
int targetWidth = Math.min(width, 4096);
int targetHeight = Math.min(height, 4096);
if (targetWidth != width || targetHeight != height) {
originalImage = resizeImage(originalImage, targetWidth, targetHeight);
}
while (toByteArray(originalImage, "jpg").length > 4 * 1024 * 1024) {
targetWidth = (int) (targetWidth * 0.9);
targetHeight = (int) (targetHeight * 0.9);
originalImage = resizeImage(originalImage, targetWidth, targetHeight);
}
}
byte[] imageData = toByteArray(originalImage, "jpg");
// save the image data to a file or MultipartFile
// ...
}
}
```
在上述代码中,`readImage()`函数用于从指定的URL读取图片,`resizeImage()`函数用于调整图片大小,`toByteArray()`函数用于将图片转换为字节数组。当读取的图片不符合要求时,通过不断调整大小来使其符合要求。最终得到的图片数据可以保存到一个文件或者MultipartFile对象中。
阅读全文