Grayscale funbktioniert nicht

bubblegumsoldie

Cadet 4th Year
Registriert
Nov. 2012
Beiträge
75
Hi!

Ich möchte ein bestimmtes Bild in ein GrayScale umwandeln, aber irgendwie stimmt etwas mit meinem Code nicht. Es zeigt einfach nur ein komplett graues bild an:

Code:
public static ImageIcon greyScale(String p)
	{
		ImageIcon old = new ImageIcon(p);
		BufferedImage Img = new BufferedImage(old.getIconWidth(), old.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
		Img.getGraphics().drawImage(old.getImage(), 0,0, null);
		for (int x = 0; x < Img.getWidth(); ++x)
		{
			for (int y = 0; y < Img.getHeight(); ++y)
			{
				int rgb = Img.getRGB(x, y);
				int r = (rgb >> 16) & 0xFF;
				int g = (rgb >> 8) & 0xFF;
				int b = (rgb & 0xFF);
				
				int gray = (r + g + b) / 3;
				//System.out.println("R: " + r + " G: " + g + " B: " + b + " -> GRAY: " + gray);
				Img.setRGB(x, y, gray);
				
		    }
		}
		return new ImageIcon(Img);
	}
 
Ich weis nicht wieso du nur ein komplett graues Bild bekommst aber theoretisch schreibst du nur in den Blaukanal deines neuen Bildes.
Entweder nimmst du ein BufferedImage.TYPE_BYTE_GRAY oder du musst deinen gemittelten Wert auch für den Rot und Grünkanal nehmen.
Also so wenn ich mich nicht irre:
Code:
int mean = (r + g + b) / 3;
int gray = (mean << 16) | (mean << 8) | mean;
Aber sonst müsstest du ja eigentlich schonmal irgendwas in Blau sehen können. Hm
Stimmen denn die Farbwerte wenn du die println Zeile drin stehen hast?
 
Zuletzt bearbeitet:
hi ich habs jetzt raus :D

Vielen Dank :)

sieht jetzt so aus

Code:
BufferedImage Img = new BufferedImage(old.getIconWidth(), old.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
		Img.getGraphics().drawImage(old.getImage(), 0,0, null);
		for (int x = 0; x < Img.getWidth(); ++x)
		{
			for (int y = 0; y < Img.getHeight(); ++y)
			{
				int rgb = Img.getRGB(x, y);
				int r = (rgb >> 16) & 0xFF;
				int g = (rgb >> 8) & 0xFF;
				int b = (rgb & 0xFF);
				
				int gray = (r + g + b) / 3;
				//System.out.println("R: " + r + " G: " + g + " B: " + b + " -> GRAY: " + gray);
				Img.setRGB(x, y, new Color(gray, gray, gray).getRGB());
		    }
		}
		return new ImageIcon(Img);
 
Zurück
Oben