免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3195 | 回复: 0
打印 上一主题 下一主题

ColorModel例子 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-25 19:58 |只看该作者 |倒序浏览
以下ColorModel例子,均从网络收集,部分未测试过,见谅。
ColorModel: getComponents(int pixel, int[] components, int offset)
(出自:
http://whf.poac.ac.cn/codeopen/jiaocheng/java2s/Code/JavaAPI/java.awt.image/ColorModelgetComponentsintpixelintcomponentsintoffset.htm


import java.awt.Color;
import java.awt.image.ColorModel;
import java.awt.image.IndexColorModel;

public class MainClass {
  public static void main(String[] args) throws Exception {
    byte ff = (byte) 0xff;
    byte[] r = { ff, 0, 0, ff, 0 };
    byte[] g = { 0, ff, 0, ff, 0 };
    byte[] b = { 0, 0, ff, ff, 0 };

    ColorModel cm = new IndexColorModel(3, 5, r, g, b);

    Color[] colors = { new Color(255, 0, 0), new Color(0, 255, 0), new Color(0, 0, 255)};

    for (int i = 0; i  " + ((byte[]) pixel)[0]);
    }

    for (byte i = 0; i  unnormalized components");
      for (int j = 0; j

Creating a Buffered Image from an Array of Color-Indexed Pixel Values
(出自:
http://www.exampledepot.com/egs/java.awt.image/Mandelbrot2.html
)
This example demonstrates how to convert a byte array of pixel values that are indices to a color table into a BufferedImage. In particular, the example generates the Mandelbrot set in a byte buffer and combines this data with a SampleModel, ColorModel, and Raster into a BufferedImage. A 16-color index color model is used to represent the pixel colors.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
   
    // Instantiate this class and then use the draw() method to draw the
    // generated on the graphics context.
    public class Mandelbrot2 {
        // Holds the generated image
        Image image;
   
        // 16-color model; this method is defined in
        //
e660 Creating an Image from an Array of Color-Indexed Pixel Values
        ColorModel colorModel = generateColorModel();
   
        public Mandelbrot2(int width, int height) {
            // Initialize with default location
            this(width, height, new Rectangle2D.Float(-2.0f, -1.2f, 3.2f, 2.4f));
        }
   
        public Mandelbrot2(int width, int height, Rectangle2D.Float loc) {
            // Generate the pixel data; this method is defined in
            //
e660 Creating an Image from an Array of Color-Indexed Pixel Values
            byte[] pixels = generatePixels(width, height, loc);
   
            // Create a data buffer using the byte buffer of pixel data.
            // The pixel data is not copied; the data buffer uses the byte buffer array.
            DataBuffer dbuf = new DataBufferByte(pixels, width*height, 0);
   
            // The number of banks should be 1
            int numBanks = dbuf.getNumBanks(); // 1
   
            // Prepare a sample model that specifies a storage 4-bits of
            // pixel datavd in an 8-bit data element
            int bitMasks[] = new int[]{(byte)0xf};
            SampleModel sampleModel = new SinglePixelPackedSampleModel(
                DataBuffer.TYPE_BYTE, width, height, bitMasks);
   
            // Create a raster using the sample model and data buffer
            WritableRaster raster = Raster.createWritableRaster(sampleModel, dbuf, null);
   
            // Combine the color model and raster into a buffered image
            image = new BufferedImage(colorModel, raster, false, null);//new java.util.Hashtable());
        }
   
        public void draw(Graphics g, int x, int y) {
            g.drawImage(image, x, y, null);
        }
    }
Here's some code that uses the Mandelbrot2 class:
    class RunMandelbrot2 {
        static public void main(String[] args) {
            new RunMandelbrot2();
        }
        RunMandelbrot2() {
            Frame frame = new Frame("Mandelbrot2 Set");
            frame.add(new MyCanvas());
            frame.setSize(300, 200) ;
            frame.setVisible(true);
        }
   
        class MyCanvas extends Canvas {
            Mandelbrot2 mandelbrot;
   
            MyCanvas() {
                // Add a listener for resize events
                addComponentListener(new ComponentAdapter() {
                    // This method is called when the component's size changes
                    public void componentResized(ComponentEvent evt) {
                        Component c = (Component)evt.getSource();
   
                        // Get new size
                        Dimension newSize = c.getSize();
   
                        // Regenerate the image
                        mandelbrot = new Mandelbrot2(newSize.width, newSize.height);
                        c.repaint();
                    }
                });
            }
   
            public void paint(Graphics g) {
                if (mandelbrot != null) {
                    mandelbrot.draw(g, 0, 0);
                }
            }
        }
    }

Convert to BufferedImage with IndexColorModel   
(出自:
http://forums.sun.com/thread.jspa?threadID=475061
)
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;

public class ColorModelConvert {
    public static void main(String[] args) {
        BufferedImage image0 = toTransparent(toICM(createSample("icm alias", true, true)));
        BufferedImage image1 = toTransparent(toICM(createSample("icm", true, false)));
        BufferedImage image2 = toTransparent(toICM(createSample("!icm alias", false, true)));
        BufferedImage image3 = toTransparent(toICM(createSample("!icm", false, false)));
        display(image0, image1, image2, image3);
    }

    public static BufferedImage createSample(String text, boolean index, boolean alias) {
        //opaque:
        BufferedImage result = new BufferedImage(450, 150,
            index ? BufferedImage.TYPE_BYTE_INDEXED : BufferedImage.TYPE_INT_RGB);
        Graphics2D g = result.createGraphics();
        if (alias) {
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        }
        g.setPaint(Color.BLUE);
        g.fillOval(100,25,100,100);
        g.setPaint(Color.RED);
        g.setFont(new Font("Lucida Bright", Font.PLAIN, 96));
        g.drawString(text, 10, 90);
        g.dispose();
        return result;
    }

    public static BufferedImage toICM(BufferedImage image) {
        if (!(image.getColorModel() instanceof IndexColorModel)) {
            //This new BI is always opaque
            int w = image.getWidth(), h = image.getHeight();
            BufferedImage result = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_INDEXED);
            Graphics2D g = result.createGraphics();
            //doesn't seem to work: :-(
            g.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE);
            g.drawRenderedImage(image, null);
            g.dispose();
            image.flush();
            return result;
        } else
            return image;
    }

    //black to transparent
    static BufferedImage toTransparent(BufferedImage image) {
        ColorModel cm = image.getColorModel();
        if (cm instanceof IndexColorModel) {
            IndexColorModel icm = (IndexColorModel) cm;
            int[] cmap = new int[icm.getMapSize()];
            icm.getRGBs(cmap);
            int color = 0xFF000000;
            int i;
            for(i=0; i!=cmap.length; ++i)
                if (cmap == color)
                    break;
            if (i != cmap.length) {
                cmap = 0; //transparent
                IndexColorModel newicm = new IndexColorModel(8, cmap.length, cmap,
                    0, true, Transparency.BITMASK, DataBuffer.TYPE_BYTE);
                BufferedImage result = new BufferedImage(newicm, image.getRaster(), false, null);
                image.flush();
                return result;
            } else
                throw new IllegalArgumentException("color not found");
        } else
            throw new IllegalArgumentException("not an IndexColorModel");
    }

    public static void display(BufferedImage image0, BufferedImage image1,
        BufferedImage image2, BufferedImage image3) {
        JPanel panel = new JPanel(new GridLayout(0,1));
        panel.add(createLabel(image0));
        panel.add(createLabel(image1));
        panel.add(createLabel(image2));
        panel.add(createLabel(image3));

        JFrame f = new JFrame("ColorModelConvert");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setContentPane(panel);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static JLabel createLabel(BufferedImage image) {
        JLabel label = new JLabel(new ImageIcon(image));
        label.setOpaque(true);
        label.setBackground(Color.WHITE);
        label.setBorder(BorderFactory.createEtchedBorder());
        return label;
    }
}

Noise Image
(出自:
http://java.poac.ac.cn/codeopen/jiaocheng/java2s/code/Java/2D-Graphics-GUI/NoiseImage.htm
)
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.awt.image.IndexColorModel;
import java.awt.image.Raster;
import java.awt.image.WritableRaster;
import java.util.Random;

import javax.swing.JComponent;
import javax.swing.JFrame;

public class StaticGenerator extends JComponent implements Runnable {
  byte[] data;

  BufferedImage image;

  Random random;

  public void initialize() {
    int w = getSize().width, h = getSize().height;
    int length = ((w + 7) * h) / 8;
    data = new byte[length];
    DataBuffer db = new DataBufferByte(data, length);
    WritableRaster wr = Raster.createPackedRaster(db, w, h, 1, null);
    ColorModel cm = new IndexColorModel(1, 2, new byte[] { (byte) 0, (byte) 255 }, new byte[] {
        (byte) 0, (byte) 255 }, new byte[] { (byte) 0, (byte) 255 });
    image = new BufferedImage(cm, wr, false, null);
    random = new Random();
    new Thread(this).start();
  }

  public void run() {
    while (true) {
      random.nextBytes(data);
      repaint();
      try {
        Thread.sleep(1000 / 24);
      } catch (InterruptedException e) { /* die */
      }
    }
  }

  public void paint(Graphics g) {
    if (image == null)
      initialize();
    g.drawImage(image, 0, 0, this);
  }

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.add(new StaticGenerator());
    f.setSize(300, 300);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/65478/showart_2036951.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP