I have a GUI that downloads an image from url and after that, there is a draw button using JFileChooser that selects the downloaded image and creates color palette of that image.
@Override
public void widgetSelected(SelectionEvent e)
{
try
{
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle(txtUrl.getText());
int userSelection = fileChooser.showOpenDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION)
{
File fileToSave = fileChooser.getSelectedFile();
String fileName = fileToSave.getAbsolutePath();
BufferedImage image = null;
image = ImageIO.read(new File(fileName));
ArrayList<String> colorList = new ArrayList<String>();
Bitmap bitmap = new Bitmap(image);
Palette palette = Palette.generate(bitmap);
int vibrant = palette.getVibrantColor(0xFFFFFF);
int vibrantLight = palette.getLightVibrantColor(0xFFFFFF);
int vibrantDark = palette.getDarkVibrantColor(0xFFFFFF);
int muted = palette.getMutedColor(0xFFFFFF);
int mutedLight = palette.getLightMutedColor(0xFFFFFF);
int mutedDark = palette.getDarkMutedColor(0xFFFFFF);
String hexColor = String.format("#%06X", (0xFFFFFF & vibrant));
colorList.add(hexColor);
hexColor = String.format("#%06X", (0xFFFFFF & vibrantLight));
colorList.add(hexColor);
hexColor = String.format("#%06X", (0xFFFFFF & vibrantDark));
colorList.add(hexColor);
hexColor = String.format("#%06X", (0xFFFFFF & muted));
colorList.add(hexColor);
hexColor = String.format("#%06X", (0xFFFFFF & mutedLight));
colorList.add(hexColor);
hexColor = String.format("#%06X", (0xFFFFFF & mutedDark));
colorList.add(hexColor);
drawPalet(fileName, colorList);
System.out.println(colorList);
JOptionPane.showMessageDialog(null, "DRAWING IS FINISHED");
}
}
catch(Exception ex)
{
System.out.println("CAN'T DRAW!");
ex.getMessage();
}
}
});
btnDraw.setBounds(210, 117, 90, 30);
btnDraw.setText("Draw");
}
public static void drawPalet(String fileName, ArrayList<String> colorList)
{
BufferedImage b_img = new BufferedImage(500, 100,BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = b_img.createGraphics();
int i=0;
for(String color:colorList)
{
java.awt.Color colorAwt = new java.awt.Color(hex2Rgb(color, 0), hex2Rgb(color, 1), hex2Rgb(color, 2));
graphics.setBackground(colorAwt);
graphics.fillRect(i, 0, 100, 100);
i=+100;
}
File outputfile = new File(fileName + "_drawed.jpg");
try
{
ImageIO.write(b_img, "jpg", outputfile);
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static int hex2Rgb(String colorStr, int val)
{
if(val == 0)
return Integer.valueOf(colorStr.substring(1, 3), 16);
else if (val == 1)
return Integer.valueOf(colorStr.substring(3, 5), 16);
else if(val == 2)
return Integer.valueOf(colorStr.substring(5, 7), 16);
else
return 0;
}
The image for to use to create custom color palette:
But the codes create an image like this:
50% is white, 50% black. But it should create an image contains green and white colors. What am I doing wrong?
Aucun commentaire:
Enregistrer un commentaire