gpt4 book ai didi

java - 我怎样才能用java像素化jpg?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:42:48 25 4
gpt4 key购买 nike

我正在尝试使用 Java 6 对 JPEG 像素化,但运气不佳。它需要与 Java 一起使用 - 而不是像 Photoshop 这样的图像处理程序,并且它需要看起来很老派 - 就像这样:

Pixelated Image

谁能帮帮我?

最佳答案

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

示例代码如下。您至少需要这些导入:javax.imageio.ImageIOjava.awt.image.BufferedImagejava.awt.image.Rasterjava.awt.image.WritableRasterjava.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[] 像素 只是 RGB 颜色值。例如,当我转储单个像素时,它看起来像 {204.0, 197.0, 189.0},浅棕褐色。

关于java - 我怎样才能用java像素化jpg?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15777821/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com