有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java BuffereImage“块”模糊问题

我目前正在尝试创建一个简单的(基于步骤的)级别生成算法。到目前为止,它正在生产一款我很满意的产品,但是由于某种原因,图像的像素被更改为一系列不同的灰色,尽管我的代码只允许两种颜色(黑色和白色)。特别奇怪的是,像素的改变只在图像本身周围成片发生

有没有办法摆脱这种奇怪的“模糊”效应

图像生成代码:

package com.ryan.game.level;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

public class RandomLevelGenerator
{
    public BufferedImage generateLevel(int maxTiles)
    {
        BufferedImage levelImage = new BufferedImage(128, 128, BufferedImage.TYPE_3BYTE_BGR);
        Color customColor = new Color(255, 255, 255);
        int myColor = customColor.getRGB();
        int xPos = 64;
        int yPos = 64;

        for(int i = maxTiles; i > 0; i--)
        {
            levelImage.setRGB(xPos, yPos, myColor); //Sets current pos to white (Floor tile)

            while(true)
            {
                Random rand = new Random();

                //=== One is up, Two is Right, Three is Down, Four is Left ===//
                int direction = rand.nextInt(4) + 1; //Generates number 1-4

                if (direction == 1 && yPos != 1) //Going up
                {
                    yPos -= 1;
                    break;
                }
                if (direction == 2 && xPos != 127) //Going right
                {
                    xPos += 1;
                    break;
                }
                if (direction == 3 && yPos != 127) //Going down
                {
                    yPos += 1;
                    break;
                }
                if (direction == 4 && xPos != 1) //Going left
                {
                    xPos -= 1;
                    break;
                }
            }
        }

        File f = new File("imageTest.jpg");
        try
        {
            ImageIO.write(levelImage, "jpg", f);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return levelImage;
    }
}

生成的图像(每次运行代码时,图像都会发生变化,但始终会对其产生这种影响):放大图片,以查看它的大小

enter image description here


共 (1) 个答案

  1. # 1 楼答案

    您正在以JPEG格式写入图像,这是一种有损格式。尤其是,JPEG不太擅长表示强度的阶跃变化——图像中会出现所谓的“振铃”伪影

    这是因为JPEG使用离散余弦变换来表示图像,即图像是平滑变化函数的加权和。这通常是可以接受的(或者,至少,不明显),当你使用JPEG的自然照片,因为大多数图像具有平滑变化的强度

    将输出格式更改为无损输出格式;试试PNG