java 图片的放大与缩小--等距采样算法

package test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/*
 * 通过像素的缩放技术,改变图片的大小
 * --等距采样法
 */
public class ImageChange {
	private  String filePath;//需要修改的图片途径
	private BufferedImage oldBufferedImage;//修改图片的图片缓冲区
	private String newFilePath;//新的图片路径
	public ImageChange(String filePath,String newFilePath) throws IOException{
		this.filePath=filePath;
		this.newFilePath=newFilePath;
		oldBufferedImage = ImageIO.read(new File(this.filePath));
	}
	/**
	 * 
	 * @param width 改变后图片的宽
	 * @param heigth 改变后图片的高
	 * @throws IOException 
	 */
	public void flex(float width,float height) throws IOException{
		//1原来宽和高与新的宽高的比例K
		/**
		 -------------------------------------------
		 ******************
		 ******************
		 ****************** 
		 ****************** 
		 ****************** 
		 把原来的图形像素填充到更大的区域里面去,分到大的空间,每一份的比例
		 ********************************
		 ********************************
		 ********************************
		 ********************************
		 ********************************
		 ********************************
		 ********************************
		 ---------------------------------------------
		 */
		float kx = oldBufferedImage.getWidth()/width;//新的图片的宽占原来像素的大小
		float ky = oldBufferedImage.getHeight()/height;//新的图片的高占原来像素的大小
		
		int startX=0,startY=0,offset=0;//初始定义值,具体含义见上一篇blog
		int oldWidth = oldBufferedImage.getWidth();
		int scansize= oldWidth;//扫描间距
		int oldHeight = oldBufferedImage.getHeight();
		int newWidth = (int) (oldWidth/kx);//新图片宽
		int newHeight = (int) (oldHeight/ky);//新图片高
		//获取旧的像素数组
		 int[] pix = new int[offset+(int) (oldHeight-startY)*scansize+(oldWidth-startX)];
		 oldBufferedImage.getRGB(startX, startY, oldWidth, oldHeight, pix, offset, scansize);
		//新的像素数组定义
		 
		 int newStartX=0,newStartY=0,newOffset=0;
		 int newScansize=newWidth;
		 System.out.print(newScansize);
		 int[] newPix = new int[newOffset+(int) (newHeight-newStartY)*newScansize+(newWidth-newStartX)]; 
		 for(int x = 0;x<newWidth-startX;x++){//遍历每一个行
			 for(int y=0; y<newHeight-startY;y++){//遍历每一个列
				 newPix[newOffset+(y-newStartY)*newScansize+(x-newStartX)]  = pix[offset+((int)((y-startY)*ky))*scansize+(int)((x-startX)*kx)];
			//这里取值的时候记得用变量乘以头先算出来的比例	
			 }
		 }
		 BufferedImage imgOut = new BufferedImage(newWidth,newHeight,oldBufferedImage.getType());  
		 imgOut.setRGB(newStartX, newStartY, newWidth, newHeight, newPix, newOffset, newScansize); 
		 ImageIO.write(imgOut, "jpg", new File(newFilePath));
	}
	
	
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值