这段代码将图像文件"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());
}
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
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.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();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18