这段代码将图像文件"original.jpg"的大小调整为宽度300像素,高度200像素,并将调整后的图像保存为"resized.jpg"。您可以根据需要修改输入和输出的文件路径和名称。
1. 方法一
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
public class ImageResize {
public static byte[] resizeImage(byte[] imageData, int width, int height) throws IOException {
ByteArrayInputStream bis = new ByteArrayInputStream(imageData);
BufferedImage image = ImageIO.read(bis);
Image resizedImage = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage bufferedResizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
bufferedResizedImage.getGraphics().drawImage(resizedImage, 0, 0, null);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bufferedResizedImage, "jpg", bos);
byte[] resizedImageData = bos.toByteArray();
bis.close();
bos.close();
return resizedImageData;
}
public static void main(String[] args) {
try {
byte[] originalImageData = Files.readAllBytes(new File("original.jpg").toPath());
byte[] resizedImageData = resizeImage(originalImageData, 300, 200);
Files.write(new File("resized.jpg").toPath(), resizedImageData);
System.out.println("图片调整大小成功!");
} catch (IOException e) {
System.out.println("图片调整大小失败: " + e.getMessage());
}
}
}
2. 方法二
public static byte[] resizeImage(byte[] finalImage, int width, int height) {
try {
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageByte));
//创建新图片
BufferedImage image = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, newWidth, newHeight);
//g2d.drawImage(img, (newWidth - img.getWidth()) / 2, (newHeight - img.getHeight()) / 2, null);
g2d.drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null);
g2d.dispose();
ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", byteArrayOut);
finalImage = byteArrayOut.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
}
文章来源地址https://www.toymoban.com/news/detail-716091.html
文章来源:https://www.toymoban.com/news/detail-716091.html
到了这里,关于将图片的大小(分辨率)调整为指定的宽度和高度的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!