如何使用Java像素化jpg? [英] How can I pixelate a jpg with java?

查看:300
本文介绍了如何使用Java像素化jpg?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java 6将JPEG像素化,但运气不佳.它必须使用Java-而不是像Photoshop这样的图像处理程序,并且需要看起来很老套-像这样:

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:

有人可以帮助我吗?

推荐答案

使用java.awt.image( javadoc )API,您可以轻松遍历图像的像素并自己执行像素化.

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.

示例代码如下.您至少需要这些导入:javax.imageio.ImageIOjava.awt.image.BufferedImagejava.awt.image.Rasterjava.awt.image.WritableRasterjava.io.File.

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.

示例:

// 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"));


据我所知,double[] pixel只是RGB颜色值.例如,当我转储单个像素时,它看起来像{204.0, 197.0, 189.0},浅棕褐色.


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.

这篇关于如何使用Java像素化jpg?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆