加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

我怎么能用java像素化jpg?

发布时间:2020-12-15 02:48:02 所属栏目:Java 来源:网络整理
导读:我正在尝试使用 Java 6对JPEG进行像素化并且没有太多运气.它需要与Java一起 – 不是像Photoshop那样的图像处理程序,它需要看起来像老学校 – 像这样: 有谁能够帮我? 解决方法 使用java.awt.image( javadoc)和javax.imageio( javadoc)API,您可以轻松地遍历
我正在尝试使用 Java 6对JPEG进行像素化并且没有太多运气.它需要与Java一起 – 不是像Photoshop那样的图像处理程序,它需要看起来像老学校 – 像这样:

有谁能够帮我?

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读