【问题标题】:Strange color behavior with Graphics2D setColorGraphics2D setColor 的奇怪颜色行为
【发布时间】:2015-02-02 07:15:45
【问题描述】:

我正在拍摄一张图像并在上面绘制一个矩形,但问题是某些图像的矩形颜色很好,但其他图像的颜色会发生变化。我该如何解决这种行为

这是我的代码

public class Index {
static int[][] coordenadas = new int[1][4];
public static void main(String[] args) throws IOException {

    coordenadas[0][0]=530;
    coordenadas[0][1]=237;
    coordenadas[0][2]=86;
    coordenadas[0][3]=17;
    //File file = new File("C:\\Users\\Juan\\Desktop\\2.jpg");
    File file = new File("C:\\Users\\Juan\\Desktop\\1.jpg");
    paint(file);
}

public static void paint(File file) throws IOException{
    BufferedImage img = ImageIO.read(file);
    Graphics2D g = img.createGraphics();    
    g.setColor(Color.yellow);            
    //g.drawRect(coordenadas[0][0], coordenadas[0][2], coordenadas[0][2], coordenadas[0][3]);           
   g.fillRect(coordenadas[0][0], coordenadas[0][3], coordenadas[0][2], coordenadas[0][3]);



    g.dispose();

    ImageIO.write(img,"jpg", new File("C:\\Users\\Juan\\Desktop\\outcome.jpg"));   
}
}

这是 2 个不同输出的示例

输出错误

右输出

这些是原始图像的链接

http://imageshack.com/a/img661/1940/bqwmPL.jpg

http://imageshack.com/a/img903/1447/vDwVtf.jpg

提前感谢您的时间和回答

【问题讨论】:

  • 一些错误(一切都在 Oracle 教程 Graphics2D 中) 1. 永远不要在密集绘制中加载图像或文件,2. 在这种情况下使用paintComponent 或paintIcon 更好,3. 坐标不应该是相对的硬编码值
  • 您好 @mKorbel 先生,感谢您的评论,coordenadas 是相对的,我刚刚在此处发布了硬编码值以显示目的。关于paintComponent 或paintIcon 的使用我不明白如何在我的目标中使用,您对如何从磁盘加载图像有什么建议吗?我正在使用这种方法docs.oracle.com/javase/tutorial/2d/images/loadimage.html提前谢谢。

标签: java awt paint graphics2d


【解决方案1】:

根据@mrKobel 的建议,我改变了加载图像的方式,从文件到 ImageIcon,一切正常。这是新代码。

public class Index {

static int[][] coordenadas = new int[1][4];
static BufferedImage bi ;
public static void main(String[] args) throws IOException {

    coordenadas[0][0]=530;
    coordenadas[0][1]=237;
    coordenadas[0][2]=86;
    coordenadas[0][3]=17;   
    ImageIcon img = new ImageIcon("C:\\Users\\Juan\\Desktop\\2.jpg");       
     BufferedImage image = new BufferedImage(img.getIconWidth(), img.getIconHeight(),  BufferedImage.TYPE_INT_RGB);
     Graphics2D g2d = (Graphics2D)image.getGraphics();
     img.paintIcon(null, g2d, 0, 0);
     Color color = new Color(255,255,0,100);
     g2d.setColor(color);               
     g2d.fillRect(coordenadas[0][0], coordenadas[0][1], coordenadas[0][2], coordenadas[0][3]);      
     ImageIO.write( image,"jpg", new File("C:\\Users\\Juan\\Desktop\\outcome.jpg"));   


}


}

【讨论】:

    猜你喜欢
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2013-12-25
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多