问题
我正在使用imgscalrJava库来调整图像大小。
resize()方法调用的结果是BufferedImage对象。我现在想把它保存为文件(通常是.jpg)。
我怎样才能做到这一点?我想从BufferedImage-> File开始,但也许这不是正确的做法?
#1 热门回答(184 赞)
File outputfile = new File("image.jpg");
ImageIO.write(bufferedImage, "jpg", outputfile);
#2 热门回答(19 赞)
你可以使用javax.imageio.ImageIOclass的write方法保存aBufferedImage对象。方法的签名是这样的:
public static boolean write(RenderedImage im, String formatName, File output) throws IOException
Hereim是要写的RenderedImage,formatName是包含格式的非正式名称的字符串(例如png)而output是要写入的文件对象。 PNG文件格式的方法示例用法如下所示:
ImageIO.write(image, "png", file);
#3 热门回答(8 赞)
创建java.awt.image.bufferedImage并将其保存到文件:
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
public static void main(String args[]){
try{
BufferedImage img = new BufferedImage(
500, 500, BufferedImage.TYPE_INT_RGB );
File f = new File("MyFile.png");
int r = 5;
int g = 25;
int b = 255;
int col = (r << 16) | (g << 8) | b;
for(int x = 0; x < 500; x++){
for(int y = 20; y < 300; y++){
img.setRGB(x, y, col);
}
}
ImageIO.write(img, "PNG", f);
}
catch(Exception e){
e.printStackTrace();
}
}
}
注意:-创建名为MyFile.png的文件。
图像为500 x 500像素。
覆盖现有文件。
图像的颜色为黑色,顶部有蓝色条纹。