图片 像素 化 java,如何使用Java像素化jpg?

I'm trying to pixelate a JPEG with Java 6 and not having much luck. It needs to be with Java - not an image manipulation program like Photoshop, and it needs to come out looking old school - like this:

3VAtB.gif

Can anybody help me?

解决方案

Using the java.awt.image (javadoc) and javax.imageio (javadoc) APIs, you can easily loop through the image's pixels and perform the pixelation yourself.

Example code follows. You will need at least these imports: javax.imageio.ImageIO, java.awt.image.BufferedImage, java.awt.image.Raster, java.awt.image.WritableRaster, and java.io.File.

Example:

// How big should the pixelations be?

final int PIX_SIZE = 10;

// Read the file as an Image

img = ImageIO.read(new File("image.jpg"));

// Get the raster data (array of pixels)

Raster src = img.getData();

// Create an identically-sized output raster

WritableRaster dest = src.createCompatibleWritableRaster();

// Loop through every PIX_SIZE pixels, in both x and y directions

for(int y = 0; y < src.getHeight(); y += PIX_SIZE) {

for(int x = 0; x < src.getWidth(); x += PIX_SIZE) {

// Copy the pixel

double[] pixel = new double[3];

pixel = src.getPixel(x, y, pixel);

// "Paste" the pixel onto the surrounding PIX_SIZE by PIX_SIZE neighbors

// Also make sure that our loop never goes outside the bounds of the image

for(int yd = y; (yd < y + PIX_SIZE) && (yd < dest.getHeight()); yd++) {

for(int xd = x; (xd < x + PIX_SIZE) && (xd < dest.getWidth()); xd++) {

dest.setPixel(xd, yd, pixel);

}

}

}

}

// Save the raster back to the Image

img.setData(dest);

// Write the new file

ImageIO.write(img, "jpg", new File("image-pixelated.jpg"));

Edit: I thought I should mention -- the double[] pixel is, as far as I can tell, just the RGB color values. For example, when I dumped a single pixel, it looked like {204.0, 197.0, 189.0}, a light tan color.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值