Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

image - Colorize a picture in java

I would like, for a java project, to change the color of a hair modelisation (to change hair color) with shadows and reflects... In fact, I wondered if there's a class which can change the color of a picture with a RGB code. If this can help you, here's the picture I need to colorize :

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I assume that the question targeted NOT at blindly replacing certain pixels with a certain (fixed) color, but at really "dyeing" the image. Once I wrote a sample class showing how this could be done:

import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.swing.*;
import javax.imageio.*;

class DyeImage
{
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    new DyeImage();
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });

    }

    public DyeImage() throws Exception
    {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        BufferedImage image = ImageIO.read(new File("DRVpH.png"));
        JPanel panel = new JPanel(new GridLayout(1,0));
        panel.add(new JLabel(new ImageIcon(image)));
        panel.add(new JLabel(new ImageIcon(dye(image, new Color(255,0,0,128)))));
        panel.add(new JLabel(new ImageIcon(dye(image, new Color(255,0,0,32)))));
        panel.add(new JLabel(new ImageIcon(dye(image, new Color(0,128,0,32)))));
        panel.add(new JLabel(new ImageIcon(dye(image, new Color(0,0,255,32)))));
        f.getContentPane().add(panel);
        f.pack();
        f.setVisible(true);
    }


    private static BufferedImage dye(BufferedImage image, Color color)
    {
        int w = image.getWidth();
        int h = image.getHeight();
        BufferedImage dyed = new BufferedImage(w,h,BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = dyed.createGraphics();
        g.drawImage(image, 0,0, null);
        g.setComposite(AlphaComposite.SrcAtop);
        g.setColor(color);
        g.fillRect(0,0,w,h);
        g.dispose();
        return dyed;
    }

}

The result with the given image and different dyeing colors will look like this:

DyedImages01


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...