-
图像直接缩放
x1=kx0
y1=ky0
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
/**
* 图像缩放(直接法)
* x1=k*x0
* y1=k*y0
* */
public class ch4_2 {
public static int BGCOLOR=0; //设置背景色,0表示黑色
public static void main(String[] args) throws Exception {
long t1=System.currentTimeMillis(); //获取程序运行前的时间,单位毫秒
BufferedImage bi=ImageIO.read(new File("1.jpg")); //读取图像
BufferedImage nbi=suofang(bi,1.5); //处理图像
ImageIO.write(nbi, "jpg", new File("1b.jpg")); //输出图像
long t2=System.currentTimeMillis(); //获取程序运行后的时间
System.out.println("程序运行"+(t2-t1)+"毫秒"); //程序结束后进行提示
}
/**
* 图像直接缩放
* @param BufferedImage bi 原始图像
* @param double k 缩放系数
* @return BufferedImage 变换后图像
* */
public static BufferedImage suofang(BufferedImage bi, double k) {
int w1=(int) (k*bi.getWidth()); //得到图像的宽度
int h1=(int) (k*bi.getHeight()); //得到图像的高度
BufferedImage nbi=new BufferedImage(w1, h1, BufferedImage.TYPE_3BYTE_BGR);
//创建新图像(临时图像变量)
//循环遍历每一个像素点
for(int y1=0;y1<h1;y1++) {
for(int x1=0;x1<w1;x1++) {
//计算输出图像坐标(x,y)所对应原图中的坐标(x0,y0)位置
int x0=(int)(x1/k);
int y0=(int)(y1/k);
int rgb=BGCOLOR; //默认像素值是背景色
if(x0>=0 && x0<bi.getWidth() && y0>=0 && y0<bi.getHeight()) { //原图坐标符合要求才赋值
rgb=bi.getRGB(x0, y0);
}
nbi.setRGB(x1, y1, rgb); //设置输出图像坐标为(x,y)的像素值
}
}
return nbi;
}
}