画像のサイズ(解像度)を指定された幅と高さに変更します。

このコードは、画像ファイル「original.jpg」を幅 300 ピクセル、高さ 200 ピクセルにサイズ変更し、サイズ変更した画像を「resize.jpg」として保存します。必要に応じて、入力ファイルと出力ファイルのパスと名前を変更できます。

1. 方法 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.方法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();
     }
}

おすすめ

転載: blog.csdn.net/qq_49641620/article/details/133239458