java修改图片的宽高
因为一些特定的原因,限制了长传图片的大小。可以使用一下这个方法试试。
我是测试过没问题发布的。
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class UpdateImage {
/**
* java修改图片的宽高
* 参数 inPath 为文件的绝对路径
* 参数 outPath 为修改好后的保存路径
* 参数 wid 新图片的宽
*
* */
public static void main(String[] args) {
// TODO Auto-generated method stub
String inPath = "D:\\photo\\1.jpg";
String outPath ="D:\\ziliao\\1.jpg";
int wid = 120;
try {
updateImage(inPath, outPath, wid);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void updateImage(String inPath,String outPath,int wid) throws IOException{
InputStream inputStream = new FileInputStream(new File(inPath));
BufferedImage bufferedImage = ImageIO.read(inputStream);
int height = bufferedImage.getHeight(); //图片的高
int width = bufferedImage.getWidth(); //图片的宽
int newHeight =0;
int newWidth =0;
//
if(wid>width){
double s = wid/width;
newHeight = (int) ((int) height*s);
newWidth = (int) ((int) width*s);
}
if(wid<width){
double s = width/wid;
newHeight = (int) ((int) height/s);
newWidth = (int) ((int) width/s);
}
BufferedImage image = new BufferedImage(newWidth,newHeight, BufferedImage.TYPE_INT_BGR);
Graphics garphics = image.createGraphics();
garphics.drawImage(bufferedImage, 0, 0, newWidth, newHeight, null);
OutputStream outputStream = new FileOutputStream(new File(outPath));
JPEGImageEncoder j = JPEGCodec.createJPEGEncoder(outputStream);
j.encode(image);
outputStream.close();
}
}
BufferedImage.TYPE_INT_BGR:
表示一个图像,该图像具有整数像素的 8 位 RGB 颜色。 R代表红,red; G代表绿,green; B代表蓝,blue。RGB模式就是,色彩数据模式,R在高位,G在中间,B在低位。BGR正好相反。例如,如果色彩数据是24位,对于RGB模式,就是高8位是R,中间8位是G,低8位是B。一个色彩数据共24位,3个字节。