java imagefilter_java image filters[02]-过滤器初探

图片缩放应用比较多,我们看看imageFilters提供的ScaleFilter怎么完成这项工作。

首先了解怎么调用过滤器,实例代码如下:

public void imageScale(String fromPath, String toPath, int width, int height)

throws IOException {

// 定义“缩放过滤器”

ScaleFilter scaleFilter = new ScaleFilter(width, height);

BufferedImage fromImage = ImageIO.read(new File(fromPath));

//

BufferedImage toImage = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB);

// 缩放处理

scaleFilter.filter(fromImage, toImage);

// 写回指定目标文件

ImageIO.write(toImage, "jpg", new File(toPath));

}

效果如下所示:

原图:

443fedd2adc535859aff1f6510396dd5.png

处理后:

0d28d9aa95c7024f53f6737b47ee4616.png

这里没有做等比例缩放,要想实现这个功能——在图片长宽做相应处理即可!

--------------------------------------

来了解下ScaleFilter内部怎么处理的!

public BufferedImage filter( BufferedImage src, BufferedImage dst ) {

if ( dst == null ) {

ColorModel dstCM = src.getColorModel();

dst = new BufferedImage(dstCM, dstCM.createCompatibleWritableRaster( width, height ), dstCM.isAlphaPremultiplied(), null);

}

Image scaleImage = src.getScaledInstance( width, height, Image.SCALE_AREA_AVERAGING );

Graphics2D g = dst.createGraphics();

g.drawImage( scaleImage, 0, 0, width, height, null );

g.dispose();

return dst;

}

关键类:

BufferedImage

Image

Graphics2D

-----------------------------------------------

图片黑白处理(去颜色)

public void gray(String fromPath, String toPath) throws IOException {

// 定义过滤器

GrayscaleFilter filter = new GrayscaleFilter();

BufferedImage fromImage = ImageIO.read(new File(fromPath));

int width = fromImage.getWidth();

int height = fromImage.getHeight();

BufferedImage toImage = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB);

//

for (int i = 0; i < width; i++) {

for (int j = 0; j < height; j++) {

int rgb = fromImage.getRGB(i, j);

// 过滤

int grayValue = filter.filterRGB(i, j, rgb);

toImage.setRGB(i, j, grayValue);

}

}

//

ImageIO.write(toImage, "jpg", new File(toPath));

}

效果:

0ddfdf93366c0ab88b7b6eb73bb587fa.png

内部实现原理:

public int filterRGB(int x, int y, int rgb) {

int a = rgb & 0xff000000;

int r = (rgb >> 16) & 0xff;

int g = (rgb >> 8) & 0xff;

int b = rgb & 0xff;

//rgb = (r + g + b) / 3;// simple average

rgb = (r * 77 + g * 151 + b * 28) >> 8;// NTSC luma

return a | (rgb << 16) | (rgb << 8) | rgb;

}

注意点:还有一个过滤器是GrayFilter,注意和这里的GrayscaleFilter予以区别。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值