java修改图片宽高

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个字节。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值