Java AWT BufferedImage get/set image RGB/ARGB image data

Description

Java AWT BufferedImage get/set image RGB/ARGB image data


import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
  public void alterImage(BufferedImage image) {
    int width = image.getWidth(null);
    int height = image.getHeight(null);

    int[] argbData; // Array holding the ARGB data

    // Prepare the ARGB array
    argbData = new int[width * height];

    // Grab the ARGB data
    image.getRGB(0, 0, width, height, argbData, 0, width);

    // Loop through each pixel in the array
    for (int i = 0; i < argbData.length; i++) {
      argbData[i] = (argbData[i] & 0xFF00FF00);
    }//from  w  ww. j  av  a2  s.  c o  m

    // Set the return Bitmap to use this altered ARGB array
    image.setRGB(0, 0, width, height, argbData, 0, width);
  }

  @Override
  public void paintComponent(Graphics g) {
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g;
    g2d.setBackground(Color.BLACK);
    g2d.clearRect(0, 0, getParent().getWidth(), getParent().getHeight());
    // antialising
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    // image loading should be outside paintComponent(Graphics g) method
    // this is just for illustration purpose
    BufferedImage image;
    try {
      image = ImageIO.read(new File("icon.png"));
      g2d.setBackground(Color.WHITE);
      g2d.clearRect(0, 0, getParent().getWidth(), getParent().getHeight());
      if (image != null) {
        alterImage(image);
        g2d.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

  }

  public static void main(String[] args) {
    // create frame for Main
    JFrame frame = new JFrame("java2s.com");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Main Main = new Main();
    frame.add(Main);
    frame.setSize(300, 210);
    frame.setVisible(true);
  }
}



PreviousNext

Related