Convert BufferedImage to FormFile or BinaryContent

To convert formfile data into buffered image,i have used the followimg,
private BufferedImage bufferedImage;
     public BufferedImage getBufferedImage(FormFile image) throws IOException {
     if ((image != null) && (bufferedImage == null)) {
     // load file from disk using Sun's JPEGIMageDecoder
     InputStream in = image.getInputStream();
     JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(in);
     bufferedImage = decoder.decodeAsBufferedImage();
     in.close();
     return bufferedImage;
The above code is used to pass a BuuferedImage parameter to a method which is used to resize an image to thumb size.
To convert this data again into FormFile or into Binary Contentdata what should be done?

To be quite clear....
You are attempting to create java code which will then be run in a database, via a database VM, as a stored procedure.
1. Get the code to run in a regular VM first.
2. Determine, without using the image code, what happens to exceptions for java stored procedures.
3. Modify your code so it does not eat exceptions.
4. Without using your image code determine how to return an image blob using a java stored proc to something (java probably) and determine that the correct image is returned.
Notice in the above that there are serveral places where you will NOT being using the image code that you want finally. You are doing that to learn the correct way to do each.
Finally after everything works combine them with your actual image code.

Similar Messages

  • How to convert BufferedImage back to Image

    I have an Image from ImageIcon and i want to cut it using BufferedImage.getSubImage(...) and now from BufferedImage i want to turn it to Image again so that i can put in ImageIcon.
    Here is my code:
    URL img = new URL(location);
    ImageIcon imgIcon = new ImageIcon(img);
    Image image = imgIcon.getImage();
    //turn image into bufferedImage via graphic draw
    BufferedImage bi = new BufferedImage(..);
    Graphics g = bi.createGraphics();
    g.drawImage(image,0,0,null);
    bi.getSubImage(...);
    // how to turn bi back to Image newImage
    any ideas??

    More correctly, BufferedImage extends Image as Image is an abstract class and not an interface.
    Shaun

  • How to diaplay bufferedImage on a browser

    hi,
    i have a BufferedImage java object. i want to display it on the Browser... how do i do it ?\
    i tried using a jpeg encoder to convert BufferedImage into a jpeg img....but i do not want to save the jpeg image on to the disk , i only want to diaplay it. The image is generated on the fly.
    i do not want to use Applet due to security restrictions. Is there any other way to diaplay it .???
    please help me out...!!!!!

    Assuming you are using a servlet, change the HttpServletResponse contentType to be "image/jpg", and write the bytes to the response's getOutputStream(). Pretty simple.

  • How to convert jpg to wbmp?

    Please!!!
    I need someone to teach(or tell) me how to convert jpg to wbmp!
    Any help will be great!
    I tried to find on web, but nothing...
    Thanks!
    Thales

    I've never used wbmp format before, but here is a demo that I got to work:
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.imageio.*;
    import javax.swing.*;
    public class WBMPTest {
        public static void main(String[] args) throws IOException {
            URL url = new URL("http://today.java.net/jag/Image24-large.jpeg");
            BufferedImage source = ImageIO.read(url);
            BufferedImage bandw = convert(source, BufferedImage.TYPE_BYTE_BINARY);
            File file = new File("temp.wbmp");
            writeWBMP(bandw, file);
            //writeWBMP(source, file);//Only integral single-band bilevel image is supported
            BufferedImage fromFile = ImageIO.read(file);
            if (fromFile == null){
                System.err.println("read fails");
                System.exit(-1);
            JPanel cp = new JPanel(new GridLayout(0,1));
            addToPanel(cp, source, "original");
            addToPanel(cp, bandw, "black and white");
            addToPanel(cp, fromFile, "temp.wbmp");
            JFrame f = new JFrame("WBMPTest");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(cp));
            f.setSize(850, 600);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        public static BufferedImage convert(BufferedImage source, int type) {
            int w = source.getWidth(), h = source.getHeight();
            BufferedImage image = new BufferedImage(w, h, type);
            Graphics2D g = image.createGraphics();
            g.drawRenderedImage(source, null);
            g.dispose();
            return image;
        static void writeWBMP(BufferedImage image, File file) throws IOException {
            Iterator writers = ImageIO.getImageWritersBySuffix("wbmp");
            if (!writers.hasNext()) {
                System.err.println("no wbmp writers");
                System.exit(-1);
            ImageWriter writer = (ImageWriter) writers.next();
            writer.setOutput(ImageIO.createImageOutputStream(file));
            writer.write(image);
        static void addToPanel(JPanel cp, BufferedImage image, String title) {
            JLabel label = new JLabel(new ImageIcon(image));
            JPanel labelPanel = new JPanel(new GridLayout(1,1));
            labelPanel.setBorder(BorderFactory.createTitledBorder(title));
            labelPanel.add(label);
            cp.add(labelPanel);
    }The image sample format that succeeds is black-and-white (not greyscale -- each pixel is
    either black or white, not a shade of grey). When I write to switch the image that was written
    out to the colored version, I got the the commented error:
    Only integral single-band bilevel image is supported
    I don't know what color models WBMP supports, but that's not much to sing about!
    You should find out if this limitation is in the wbmp image writer or in the wbmp format itself.

  • Dithering no longer works under 1.4.2

    I had this posted in the AWT forum and I was suggested that the issue was better suited to the Java 2D forum:
    I am trying to convert a jpeg to a 1 bit per pixel Buffered image.
    The current implementation is working fine under 1.3.1_05 but not under any of the 1.4.2 JVM's that I have tried. Any tips on what I am doing wrong?
    Here is a snippet of the the code:
    // input stream is from a jpeg file:
    JPEGImageDecoder jpgDecoder = JPEGCodec.createJPEGDecoder(src);
    // decompress to a AWT buffered image. this will be our source image in the color
    // space of the original jpg.
    BufferedImage srcImg = jpgDecoder.decodeAsBufferedImage();
    // create an output buffered image in the color space that we need. in this case
    // one bit binary.
    BufferedImage destImage =null;
    Graphics2D graphics=null;
    int bufferedImageType = BufferedImage.TYPE_BYTE_BINARY;
    // cols and rows are passed in as parameters
    destImage = new BufferedImage(cols,rows,bufferedImageType);
    // create a Graphics2D context out of the Output buffered image and draw the
    // source image to it. This will convert the color space for us. At least it does under 1.3.1
    graphics=destImage.createGraphics();
    // the following commented line has the effect of inverting the color for us.
    // this would be nice except it seems to have the effect of hanging 1.3.1 JVM.
    //graphics.setXORMode(Color.WHITE);
    graphics.drawImage(srcImg,null,0,0);
    // get the data buffer from the destImage and send it back to the caller
    DataBufferByte dataBuffer = (DataBufferByte)destImage.getData().getDataBuffer();
    return dataBuffer;
    This works great under 1.3.1 The returned data buffer is merged with some other images and the result is a nicely dithered 1 bpp output image. (I am currently generating either tiff or png at 1bpp).
    Under 1.4.2 it seems that instead of dithering I get some sort of thresholding that looks awfull. No attempt to emulate grayscale is made at all.
    Has anyone encounterd this problem? I have looked through the forum but nothing similar seems to be posted.
    If you need a more concrete example I can post a main that reads the jpg, converts it to 1bpp and saves it as a tiff.
    Thanks
    Richard Seabright.

    Here is a sample class that demonstrates the issue (behaves differently under 1.4.2 than it does under 1.3.1):
    import java.awt.*;
    import java.awt.color.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class ColorConvert {
    public static void main(String[] args) {
    BufferedImage image0 = createSample();
    BufferedImage image1 = convert(image0);
    display(image0, image1);
    public static BufferedImage createSample() {
    BufferedImage result = new BufferedImage(450, 150, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = result.createGraphics();
    g.setPaint(Color.yellow);
    g.fillOval(10, 25, 100, 100);
    g.setPaint(Color.red);
    g.fillOval(80, 25, 100, 100);
    g.setPaint(Color.green);
    g.fillOval(150, 25, 100, 100);
    g.setPaint(Color.blue);
    g.fillOval(220, 25, 100, 100);
    g.dispose();
    return result;
    public static BufferedImage convert(BufferedImage image) {
    int w = image.getWidth(), h = image.getHeight();
    BufferedImage result = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_BINARY);
    Graphics2D g = result.createGraphics();
    g.drawImage(image, null, 0, 0);
    g.dispose();
    return result;
    public static void display(BufferedImage image0, BufferedImage image1) {
    JPanel panel = new JPanel(new GridLayout(0,1));
    panel.add(createLabel(image0));
    panel.add(createLabel(image1));
    JFrame f = new JFrame("ColorConvert");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setContentPane(panel);
    f.pack();
    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;
    }

  • Problem displaying CMYK jpeg images

    I have a problem with a CMYK jpeg image.
    I know that about supported JPEGs in JRE - JCS_CMYK and JCS_YCCK are not supported directly.
    And I found here how to load the image:
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4799903
    http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5100094
    I used both the suggestions described to load it, but when the image is displayed the colors are wrong, are very different from the one displayed in PhotoShop, for example.
    Any suggestion are very appreciated. If it's necessary i can send you the image.
    Roberto
    Here is the code
    package com.cesarer.example.crop;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import java.util.Iterator;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageReader;
    import javax.imageio.stream.ImageInputStream;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class CroppingRaster extends JPanel
        BufferedImage image;
        Dimension size;
        Rectangle clip;
        boolean showClip;
        public CroppingRaster(BufferedImage image)
            this.image = image;
            size = new Dimension(image.getWidth(), image.getHeight());
            showClip = false;
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int x = (getWidth() - size.width)/2;
            int y = (getHeight() - size.height)/2;
            g2.drawImage(image, x, y, this);
            if(showClip)
                if(clip == null)
                    createClip();
                g2.setPaint(Color.red);
                g2.draw(clip);
        public void setClip(int x, int y)
            // keep clip within raster
            int x0 = (getWidth() - size.width)/2;
            int y0 = (getHeight() - size.height)/2;
            if(x < x0 || x + clip.width  > x0 + size.width ||
               y < y0 || y + clip.height > y0 + size.height)
                return;
            clip.setLocation(x, y);
            repaint();
        public Dimension getPreferredSize()
            return size;
        private void createClip()
            clip = new Rectangle(140, 140);
            clip.x = (getWidth() - clip.width)/2;
            clip.y = (getHeight() - clip.height)/2;
        private void clipImage()
            BufferedImage clipped = null;
            try
                int w = clip.width;
                int h = clip.height;
                int x0 = (getWidth()  - size.width)/2;
                int y0 = (getHeight() - size.height)/2;
                int x = clip.x - x0;
                int y = clip.y - y0;
                clipped = image.getSubimage(x, y, w, h);
            catch(RasterFormatException rfe)
                System.out.println("raster format error: " + rfe.getMessage());
                return;
            JLabel label = new JLabel(new ImageIcon(clipped));
            JOptionPane.showMessageDialog(this, label, "clipped image",
                                          JOptionPane.PLAIN_MESSAGE);
        private JPanel getUIPanel()
            final JCheckBox clipBox = new JCheckBox("show clip", showClip);
            clipBox.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    showClip = clipBox.isSelected();
                    repaint();
            JButton clip = new JButton("clip image");
            clip.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    clipImage();
            JPanel panel = new JPanel();
            panel.add(clipBox);
            panel.add(clip);
            return panel;
        public static void main(String[] args) throws IOException
             File file = new File("src/ABWRACK_4C.jpg");
             // Find a JPEG reader which supports reading Rasters.
            Iterator readers = ImageIO.getImageReadersByFormatName("JPEG");
            ImageReader reader = null;
            while(readers.hasNext()) {
                reader = (ImageReader)readers.next();
                if(reader.canReadRaster()) {
                    break;
         // Set the input.
            ImageInputStream input =
                ImageIO.createImageInputStream(file);
            reader.setInput(input);
            Raster raster = reader.readRaster(0, null);
             BufferedImage bi = new BufferedImage(raster.getWidth(),
                    raster.getHeight(),
                    BufferedImage.TYPE_4BYTE_ABGR);
             // Set the image data.
             bi.getRaster().setRect(raster);
            // Cropping test = new Cropping(ImageIO.read(file));
             CroppingRaster test = new CroppingRaster(bi);
            ClipMoverRaster mover = new ClipMoverRaster(test);
            test.addMouseListener(mover);
            test.addMouseMotionListener(mover);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(test));
            f.getContentPane().add(test.getUIPanel(), "South");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class ClipMoverRaster extends MouseInputAdapter
        CroppingRaster cropping;
        Point offset;
        boolean dragging;
        public ClipMoverRaster(CroppingRaster c)
            cropping = c;
            offset = new Point();
            dragging = false;
        public void mousePressed(MouseEvent e)
            Point p = e.getPoint();
            if(cropping.clip.contains(p))
                offset.x = p.x - cropping.clip.x;
                offset.y = p.y - cropping.clip.y;
                dragging = true;
        public void mouseReleased(MouseEvent e)
            dragging = false;
        public void mouseDragged(MouseEvent e)
            if(dragging)
                int x = e.getX() - offset.x;
                int y = e.getY() - offset.y;
                cropping.setClip(x, y);
    }

    The loading process It takes about 10 seconds, and every repaint it takes the same time.The painting yes, the loading no. It shouldn't take much more time to load the image then an ordinary JPEG. In particular, your now using a "natively accelerated" JPEG image reader, so it should take less time on average to load any JPEG. 10 seconds is absurd. Are you sure your not including the drawing time in that figure?
    - Another problem: JAI-ImageIO is not available for MAC OS X platform.This is somewhat true. You can take the imageio.jar file and package it together with your program (adding it to the class path). This will give you most of the functionality of JAI-ImageIO; in particular the TIFFImageReader. You just won't be able to use the two natively accelerated ImageReaders that comes with installing.
    Right now, you're using the accelerated CLibJPEGImageReader to read the image. You can't use this image reader on the MAC, so you have to take the approach mentioned in the 2nd bug report you originally posted (i.e. use an arbitrary CMYK profile).
    The conversion is too long more than 30 seconds.The code you posted could be simplified to
    BufferedImage rgbImage = new BufferedImage(w,h,
                BufferedImage.3_BYTE_BGR);
    ColorConvertOp op = new ColorConvertOp(null);
    op.filter(cmykImage,rgbImage);But again, 30 seconds is an absurd value. After a little preparation, converting from one ICC_Profile to another is essentially a look up operation. What does,
    System.out.println(cmykImage.getColorModel().getColorSpace());print out? If it's not an instance of ICC_ColorSpace, then I can understand the 30 seconds. If it is, then something is dreadfully wrong.
    the RGB bufferedImage that i get after the transformation when it is displayed is much more brightThis is the "one last problem that pops up" that I hinted at. It's because some gamma correction is going on in the background. I have a solution, but it's programming to the implementation of the ColorConvertOp class and not the API. So I'm not sure about its portability between java versions or OS's.
    import javax.swing.*;
    import java.awt.color.ICC_ColorSpace;
    import java.awt.color.ICC_Profile;
    import java.awt.image.BufferedImage;
    import java.awt.image.ColorConvertOp;
    import javax.imageio.ImageIO;
    import java.io.File;
    public class CMYKTest {
         public static void main(String[] args) throws Exception{
            long beginStamp, endStamp;
            //load image
            beginStamp = System.currentTimeMillis();
            BufferedImage img = ImageIO.read(/*cmyk image file*/);
            endStamp = System.currentTimeMillis();
            System.out.println("Time to load image: " + (endStamp-beginStamp));
            //color convert
            BufferedImage dest = new BufferedImage(img.getWidth(),
                                                   img.getHeight(),
                                                   BufferedImage.TYPE_3BYTE_BGR);
            beginStamp = System.currentTimeMillis();
            sophisticatedColorConvert(img,dest);
            endStamp = System.currentTimeMillis();
            System.out.println("Time to color convert: " + (endStamp-beginStamp));
            //display
            JFrame frame = new JFrame();
            frame.setContentPane(new JScrollPane(new JLabel(new ImageIcon(dest))));
            frame.setSize(500,500);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        public static BufferedImage sophisticatedColorConvert(BufferedImage src,
                                                              BufferedImage dst) {
            ICC_ColorSpace srcCS =
                    (ICC_ColorSpace) src.getColorModel().getColorSpace();
            ICC_Profile srcProf = srcCS.getProfile();
            byte[] header = srcProf.getData(ICC_Profile.icSigHead);
            intToBigEndian(ICC_Profile.icSigInputClass,header,12);
            srcProf.setData(ICC_Profile.icSigHead,header);
            ColorConvertOp op = new ColorConvertOp(null);
            return op.filter(src, dst);
        private static void intToBigEndian(int value, byte[] array, int index) {
                array[index]   = (byte) (value >> 24);
                array[index+1] = (byte) (value >> 16);
                array[index+2] = (byte) (value >>  8);
                array[index+3] = (byte) (value);
    }

  • Binary conversion of a big image leads to "java.lang.OutOfMemoryError"?

    Hi,
    My program loads a black and white 1 bit depth image of around 20 - 30mb. When I try to convert it to binary image, it gives the following error: java.lang.OutOfMemoryError: Java heap spaceI am converting a bufferedimage to binaryimage. I used the following conversion method:      
    // This method converts an image to a binary image:
         public static BufferedImage convert (BufferedImage src, int type)
              int w = src.getWidth ();
              int h = src.getHeight ();
              BufferedImage dst = new BufferedImage (w, h, type);
            Graphics2D g = dst.createGraphics ();
            g.drawRenderedImage (src, null);
            g.dispose ();
              return dst;
         }The program was working well before but now it keeps giving the heap memory error which is really weird. Is there any way I can fix this? Can anybody suggest a better way to convert a black and white image to binary data. Thanks.

    You could increase maximum memory (-Xmx): [http://java.sun.com/javase/6/docs/technotes/tools/windows/java.html]

  • 16 bit Intensity to JPEG image

    Hi,
    I have an input file with 16 bit intensity values. I want to creat JPEG image from this file. Here is my source code:
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.image.*;
    import javax.imageio.ImageIO;
    public class CreateJpeg extends Frame{
    private BufferedImage img = null;
         public static int[][] getData(File f) throws IOException {
              ArrayList line = new ArrayList();
              BufferedReader br = new BufferedReader(new FileReader(f));
              String s = null;
              while ((s = br.readLine()) != null)
                   line.add(s);
              int[][] map = new int[line.size()][];
              for (int i = 0; i < map.length; i++) {
                   s = (String) line.get(i);
                   StringTokenizer st = new StringTokenizer(s, "\t");
                   int[] arr = new int[st.countTokens()];
                   for (int j = 0; j < arr.length; j++)
                        arr[j] = Integer.parseInt(st.nextToken());
                   map[i] = arr;
              return map;
         public CreateJpeg (ColorModel colorModel, WritableRaster raster)throws IOException{
              img = new BufferedImage(colorModel, raster, false, null);//new java.util.Hashtable());
              show();
              ImageIO.write( img, "jpeg" , new File("new.jpeg"));
         public void paint (Graphics g) {
    g.drawImage (img, 0, 0, this);
         public static void main(String[] args) throws Throwable {
              int[][] map = getData(new File(args[0]));
              int[] OneDimImage = new int[map.length*map[0].length];
              for (int i = 0; i < map.length; i++) {
                   for (int j = 0; j < map.length; j++){
                        OneDimImage[i * map[0].length + j] = map[i][j];
              DataBuffer dbuf = new DataBufferInt(OneDimImage, map[0].length*map.length);
    WritableRaster raster = Raster.createPackedRaster(dbuf,map[0].length, map.length,
              map[0].length, new int[] { 0xff00, 0xf0, 0xf}, null);
              ColorModel colorModel = new DirectColorModel(16, 0xff00, 0xf0, 0xf);
              new CreateJpeg(colorModel, raster);
    After compiling and running this file, I got the following messages:
    Exception in thread "main" java.lang.IllegalArgumentException: Raster IntegerInt
    erleavedRaster: width = 800 height = 938 #Bands = 3 xOff = 0 yOff = 0 dataOffset
    [0] 0 is incompatible with ColorModel DirectColorModel: rmask=ff00 gmask=f0 bmas
    k=f amask=0
    at java.awt.image.BufferedImage.<init>(BufferedImage.java:613)
    at CreateJpeg.<init>(CreateJpeg.java:28)
    at CreateJpeg.main(CreateJpeg.java:48).
    I will be pleased if anybody help me to solve this.
    Thanks

    No, short of getting a jpeg to use a lossless compression, this sequence:
    buffered image =encode=> jpeg file =decode=> buffered image
    is going to scramble data on the pixel level. If you use a high quality param value,
    like 1.0f, it will look good, but individual pixels won't be "close" to
    their original values, because that is not what the algorithm delivers.
    Demo:
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import javax.imageio.stream.*;
    public class PngEnDecoder{
        public static void main(String[] args) throws Throwable {
            int w = 256, h = 1;
            int[] OneDimImage = new int[w*h];
            for (int i=0;i<w*h;i++)
                OneDimImage=i;
    DataBuffer dbuf = new DataBufferInt(OneDimImage, OneDimImage.length);
    int[] masks = { 0xff0000, 0xff00, 0xff};
    WritableRaster raster = Raster.createPackedRaster(dbuf, w, h, w, masks, null);
    ColorModel colorModel = new DirectColorModel(24, masks[0], masks[1], masks[2]);
    BufferedImage bi1 = new BufferedImage(colorModel, raster, false, null);
    File file = new File("test.jpeg");
    write(bi1, file, 1.0f);
    BufferedImage bi2 = convert(ImageIO.read(file), BufferedImage.TYPE_INT_RGB);
    WritableRaster raster1 = bi2.getRaster();
    DataBuffer db = raster1.getDataBuffer();
    DataBufferInt dbi = (DataBufferInt) db;
    int[] data = dbi.getData();
    for (int j=0;j<data.length;j++)
    System.out.println(data[j]);
    static void write(BufferedImage bi, File file, float quality) throws IOException {
    ImageOutputStream out = ImageIO.createImageOutputStream(file);
    ImageWriter writer = (ImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next();
    writer.setOutput(out);
    ImageWriteParam param = writer.getDefaultWriteParam();
    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
    param.setCompressionQuality(quality);
    writer.write(null, new IIOImage(bi, null, null),param);
    public static BufferedImage convert(BufferedImage source, int targetType) {
    int sourceType = source.getType();
    if (sourceType == targetType)
    return source;
    System.out.println("converting image type...");
    BufferedImage result = new BufferedImage(source.getWidth(), source.getHeight(), targetType);
    Graphics2D g = result.createGraphics();
    g.drawRenderedImage(source, null);
    g.dispose();
    return result;

  • JPEG encoding-decoding of intensities

    Hi,
    I used the following code to create jpeg image from intensity values and to retrieve the intensity values by decoding the jpeg image. Everything works fine except that I got some intensity values which are negative. I don't know from where this negative intensities are coming from. Here is my code:
    import java.awt.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    public class JpegEnDecoder{
    public static void main(String[] args) throws Throwable {
    int w = 200, h = 1;
              short[] OneDimImage = new short[w*h];
    for (int i=0;i<w*h;i++)
                   OneDimImage=(short)(32500+i);
              DataBuffer dbuf = new DataBufferUShort(OneDimImage, OneDimImage.length);
              int[] masks = {0xf800, 0x07e0, 0x001f};
    WritableRaster raster = Raster.createPackedRaster(dbuf, w, h, w, masks, null);
              ColorModel colorModel = new DirectColorModel(16, masks[0], masks[1], masks[2]);
    BufferedImage bi1 = new BufferedImage(colorModel, raster, false, null);
    File file = new File("test.jpeg");
    ImageIO.write(bi1, "jpeg", file);
              int type = bi1.getType();
              BufferedImage bi2 = convert(ImageIO.read(file), BufferedImage.TYPE_USHORT_565_RGB);
    WritableRaster raster1 = bi2.getRaster();
    DataBuffer db = raster1.getDataBuffer();
              DataBufferUShort dbi = (DataBufferUShort) db;
    short[] data = dbi.getData();
    for (int j=0;j<data.length;j++)
    System.out.println(data[j]);
    public static BufferedImage convert(BufferedImage source, int targetType) {
    int sourceType = source.getType();
    if (sourceType == targetType)
    return source;
    BufferedImage result = new BufferedImage(source.getWidth(), source.getHeight(), targetType);
    Graphics2D g = result.createGraphics();
    g.drawRenderedImage(source, null);
    g.dispose();
    return result;
    I will be pleased if anybody can explain how to solve this problem. Thanks in advance.

    {noformat}_Anti{noformat}, don't double post. If you want a thread moved to a more appropriate forum, make a request in the [_current RA thread_|http://forums.sun.com/thread.jspa?threadID=5414121] in the News and Updates forum.
    I've removed your other thread on the same topic.
    db

  • Writing image to wbmp file in java

    I am having problem writing images to wbmp files by java using the javax.imageio.* class. Though wbmp is present in the list given by writer format names.
    String[] writers = ImageIO.getWriterFormatNames();
    System.out.println("Can write to -");
    for ( String s : writers)
                System.out.println(s);
            }but my code to convert an image format is not working for wbmp files
    File in=new File("star.png");
    File out=new File("def.wbmp");
    File out1=new File("def.jpg");
    BufferedImage image;
    try {
         image = ImageIO.read(in);
         ImageIO.write(image,"wbmp",out);
         ImageIO.write(image,"jpg",out1);
    } catch (IOException e) {}the jpeg file is created successfully but the wbmp file remains empty. can you tell me where the problem is. Or is there some alternative method for image conversion.

    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class WirelessPrep {
        private JPanel getContent(BufferedImage image) {
            JPanel panel = new JPanel(new GridLayout(1,0));
            panel.add(wrap(image));
            panel.add(wrap(convert(image)));
            return panel;
        private BufferedImage convert(BufferedImage image) {
            // Convert to BufferedImage.TYPE_BYTE_BINARY
            BufferedImage binary = convert(image, BufferedImage.TYPE_BYTE_BINARY);
            BufferedImage wbmp = null;
            File file = new File("wirelessPrep.wbmp");
            try {
                ImageIO.write(binary, "wbmp", file);
                wbmp = ImageIO.read(file);
            } catch(IOException e) {
                System.out.println("io error: " + e.getMessage());
            return wbmp;
        private BufferedImage convert(BufferedImage src, int type) {
            int w = src.getWidth();
            int h = src.getHeight();
            BufferedImage dst = new BufferedImage(w, h, type);
            Graphics2D g2 = dst.createGraphics();
            g2.drawImage(src, 0, 0, null);
            g2.dispose();
            return dst;
        private JLabel wrap(BufferedImage image) {
            ImageIcon icon = new ImageIcon(image);
            JLabel label = new JLabel(icon, JLabel.CENTER);
            return label;
        public static void main(String[] args) throws IOException {
            String path = "images/bison.jpg";
            BufferedImage image = ImageIO.read(new File(path));
            JPanel panel = new WirelessPrep().getContent(image);
            JOptionPane.showMessageDialog(null, panel, "", -1);
    }

  • Incorrect drawing of PNG with transparency

    Hey guys,
    I am trying to draw a small PNG image onto a JPanel. First I fill the background with red, then I draw the image.
    Everything outside the white circle is transparent so I can use it on different backgrounds.
    (The original image is here: http://homepage.mac.com/djcredo/pngproblem/up_button.png)
    However, when I draw it, the image becomes corrupted. Here is a snapshot of what it looks like:
    http://homepage.mac.com/djcredo/pngproblem/png_corruption.png
    If I make the image non-transparent, it draws fine.
    Here is my code:
    protected static BufferedImage backButton;
    static {
         try {
              backButton = ImageIO.read(new File("images/up_button.png"));
         } catch (Exception e){
              System.out.println("could not read image!");
              System.exit(1);
    // Fill some of the screen red.
    g.setColor(new Color(180,180,180));
    g.fillRect(0,currentY,width + 30,50);
    g.drawImage(backButton, width - 50, 2, null);Does anyone have suggestions what I'm doing wrong?

    Unable to replicate the poor image quality shown in your second link. Everything looks okay in this test app:
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class TransparentPng extends JPanel
        BufferedImage orig;
        BufferedImage converted;
        BufferedImage transparent;
        public TransparentPng(BufferedImage image)
            orig = image;
            converted = convert();
            transparent = createTransparentImage();
            System.out.println("orig type        = " + orig.getType() + "\n" +      // 0
                               "converted type   = " + converted.getType() + "\n" + // 2
                               "transparent type = " + transparent.getType());      // 2
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            int w = getWidth();
            int width = orig.getWidth();
            int x = (w - 3*width)/4;
            int xInc = x + width;
            g2.setPaint(Color.red);
            g2.fillRect(0,0,w,120);
            g2.drawImage(orig, x, 30, this);
            x += xInc;
            g2.drawImage(converted, x, 30, this);
            x += xInc;
            g2.drawImage(transparent, x, 30, this);
        private BufferedImage convert()
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            GraphicsDevice gd = ge.getDefaultScreenDevice();
            GraphicsConfiguration gc = gd.getDefaultConfiguration();
            int w = orig.getWidth();
            int h = orig.getHeight();
            BufferedImage bi = gc.createCompatibleImage(w, h, Transparency.TRANSLUCENT);
            Graphics2D g2 = bi.createGraphics();
            g2.drawImage(orig, 0, 0, this);
            g2.dispose();
            return bi;
        private BufferedImage createTransparentImage()
            int w = orig.getWidth();
            int h = orig.getHeight();
            BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = image.createGraphics();
            g2.setPaint(new Color(0,0,0,0));
            g2.fillRect(0,0,w,h);
            g2.drawImage(orig, 0, 0, this);
            g2.dispose();
            return image;
        private JPanel getButtonPanel()
            JPanel panel = new JPanel(new GridLayout(1,0));
            panel.add(getButton(orig));
            panel.add(getButton(converted));
            panel.add(getButton(transparent));
            return panel;
        private JButton getButton(BufferedImage image)
            JButton button = new JButton(new ImageIcon(image));
            button.setBackground(Color.red);
            return button;
        public static void main(String[] args) throws IOException
            String path = "up_button.png";
            ClassLoader cl = TransparentPng.class.getClassLoader();
            InputStream is = cl.getResourceAsStream(path);
            TransparentPng tp = new TransparentPng(ImageIO.read(is));
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(tp);
            f.getContentPane().add(tp.getButtonPanel(), "South");
            f.setSize(400,250);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Output byte[] (image) to JSP page from Servlet - not working - why??

    I'm testing some new code in my servlet. I'm changing the method I use for pulling an image from the db (which is stored in a Blob column) and then displaying it in a Jsp page via <img src="go.callServlet">
    The new way works up until the code that outputs the image (bytes).
    Here's a snippet of the code -
                   rs = stmt.executeQuery("Select image from images");
                   rs.next();
                   Blob blobimage = rs.getBlob(1);          
                   int index = 0;             
                in = blobimage.getBinaryStream();        
                BufferedImage orig = ImageIO.read(in);    
                //resize image
                GraphicsConfiguration gc = getDefaultConfiguration(); //calls method in servlet
                 BufferedImage image = toCompatibleImage(orig, gc); //calls method in servlet                   
                 final double SCALE = (double)max_Width_Large/(double)image.getWidth(null);
                 int w = (int) (SCALE * image.getWidth(null));
                 int h = (int) (SCALE * image.getHeight(null));
                 final BufferedImage resize = getScaledInstance(image, w, h, gc);
                   //convert bufferedimage to byte array
                   ByteArrayOutputStream bytestream = new ByteArrayOutputStream();                                        
                  // W R I T E                                        
                  ImageIO.write(resize,"jpeg",bytestream);                                                                      
                  byte[] bytearray = bytestream.toByteArray();
                  bytestream.flush();
                  res.reset();
                   res.setContentType("image/jpeg");                   
                   while((index=in.read(bytearray))!= -1 ) {                         
                             res.getOutputStream().write(bytearray,0,index);
                   res.flushBuffer();              
                   in.close();     
                   //....               I know for a fact that the process of getting the image as a blob, making a BufferedImage from it, having the BufferedImage resized, and then converted into a byte[] array, works! I tested by putting the result into a db table.
    I just don't understand why it is that as soon as it gets to the code where it should output the image, it doesn't work. Its frustrating:(
    Here's the code I use regularly to output the image to the jsp, works all the time. The reason I've changed the method, is because I wanted to resize the image before displaying it, and keep it to scale without losing too much quality.
    rs = stmt.executeQuery("Select image from testimages");
                   rs.next();
                   Blob blobimage = rs.getBlob(1);
                   int index = 0;             
                in = blobimage.getBinaryStream();
                  int blob_length = (int)blobimage.length();
                  byte[] bytearray = new byte[blob_length];
                  res.reset();
                  res.setContentType("image/jpeg");
                   while((index=in.read(bytearray))!= -1 ) {
                             res.getOutputStream().write(bytearray,0,index);
                   res.flushBuffer();
                   in.close();     
    //...Can someone shed some light on this trouble I'm having?
    Much appreciated.

    I hate to bother you again BalusC, but I have another question, and value your expertise.
    With regards to using the BufferedInput and Output Streams - I made the change to my code that is used for uploading an image to the db, and I hope I coded it right.
    Can you please take a look at the snippet below and see if I used the BufferedOutputStream efficiently?
    The changes I made are where I commented /*Line 55*/ and /*Line 58*/.
    Much appreciated.
         boolean isPart = ServletFileUpload.isMultipartContent(req);
             if(isPart) { //40
              // Create a factory for disk-based file items
              FileItemFactory factory = new DiskFileItemFactory();
              // Create a new file upload handler
              ServletFileUpload upload = new ServletFileUpload(factory);                    
              java.util.List items = upload.parseRequest(req); // Create a list of all uploaded files.
              Iterator it = items.iterator(); // Create an iterator to iterate through the list.                         
              int image_count = 1;
         while(it.hasNext()) {                                                       
              //reset preparedStatement object each iteration
              pstmt = null;
                 FileItem item = (FileItem)it.next();     
                 String fieldValue = item.getName();     
                 if(!item.isFormField()) {//30
              //when sent through form
              File f = new File(fieldValue); // Create a FileItem object to access the file.
              // Get content type by filename.
                 String contentType = getServletContext().getMimeType(f.getName());
                 out.print("contenttype is :"+contentType+"<br>");                    
                 if (contentType == null || !contentType.startsWith("image")) {                               
                     String message = "You must submit a file that is an Image.";
                     res.sendRedirect("testing_operations.jsp?message="+message);
                       return;
              }//if
              //#### Code Update 3/18/09 ####
    /*line 38*/     BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
              BufferedImage bug_lrg_Img = ImageIO.read(bis);                                           
              //code to resize the image;
              BufferedImage dimg = new BufferedImage(scaledW,scaledH,BufferedImage.TYPE_INT_RGB);
              //more code for resizing
              //BufferedImage dimg now holding resized image                           
                  ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
                // W R I T E
                /* Line 55 */     
                   /*  ??? - is a BufferedOutputStream more efficient to write the data */
                   BufferedOutputStream bos = new BufferedOutputStream(bytestream);
                   /*line 58 */     
                   //changed from  ImageIO.write(dimg,"jpg",bytestream);                                  
                   //to
                   ImageIO.write(dimg,"jpg",bos);
              // C L O S E
              bytestream.flush();
                   /* Line 63 */
                   byte[] newimage = bytestream.toByteArray();                    
              pstmt = conn.prepareStatement("insert into testimages values(?)");                              
              pstmt.setBytes(1,newimage);
              int a = pstmt.executeUpdate();     
                   bis.close();
                bytestream.close();
                   bos.close();
                  //...

  • How can I convert an Image ( or BufferedImage ) to Base64 format ?

    Hi folks...
    How can I convert an Image, or BufferedImage, to the Base64 format ?
    The image that I want to convert, I get from the webCam connected to the computer...
    Anyone can help me ?
    Rodrigo Kerkhoff

    I suggest you read this thread concerning this:
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=477461
    Failing that, Google is your friend.
    Good luck!

  • Converting a BufferedImage to an Image

    I have a program with some BufferedImages that the user needs to be able to drag around the screen.
    1) The dragging process is very sluggish when I use BufferedImages, but not when I use normal Images. Is this normal, or is something wrong with my program?
    2) If using Images is the only way to fix this problem, how do I draw my BufferedImages into Images or convert them to Images? They have to start out as BufferedImages so that they can undergo a one-time rescaling operation.

    Where can I find out what a profiler is and how to use one?
    Here is an abbreviated version of the code. A non-buffered Image is available for dragging here, and it too drags sluggishly unless you eliminate the line of code that draws the BufferedImages to the screen. There is probably something else wrong with this program, because at one point dragging the BufferedImages did work well. When the problem appeared I tore my code apart trying to find out what I had messed up, but after reversing all the recent changes I had not eliminated the problem and was left mystified.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.lang.*;
    import java.awt.image.*;
    import java.awt.geom.*;
    public class Hanoi2 extends JFrame implements MouseListener, MouseMotionListener, ActionListener{
         private GraphicsDevice device;
         Landscape panel=new Landscape();
         JMenuBar bar=new JMenuBar();
         JMenu menu1=new JMenu("Game");
         JMenuItem m11=new JMenuItem("New Game");
         JMenuItem m12=new JMenuItem("Save Game");
         JMenuItem m13=new JMenuItem("Load Game");
         JMenuItem m14=new JMenuItem("Exit");
         JMenu menu2=new JMenu("Options");
         JMenu m21=new JMenu("Disk Number");
         JRadioButtonMenuItem sm11=new JRadioButtonMenuItem("4");
         JRadioButtonMenuItem sm12=new JRadioButtonMenuItem("5");
         JRadioButtonMenuItem sm13=new JRadioButtonMenuItem("6");
         JRadioButtonMenuItem sm14=new JRadioButtonMenuItem("7");
         JRadioButtonMenuItem sm15=new JRadioButtonMenuItem("8");
         JRadioButtonMenuItem sm16=new JRadioButtonMenuItem("9");
         JRadioButtonMenuItem sm17=new JRadioButtonMenuItem("10");
         JMenu m22=new JMenu("Disk Set");
         JRadioButtonMenuItem sm21=new JRadioButtonMenuItem("Stone");
         JRadioButtonMenuItem sm22=new JRadioButtonMenuItem("Glass");
         JRadioButtonMenuItem sm23=new JRadioButtonMenuItem("Pattern");
         JMenu m23=new JMenu("Backdrop");
         JRadioButtonMenuItem sm31=new JRadioButtonMenuItem("Spirals");
         JRadioButtonMenuItem sm32=new JRadioButtonMenuItem("Stars");
         JRadioButtonMenuItem sm33=new JRadioButtonMenuItem("Dots and Flowers");
         JRadioButtonMenuItem sm34=new JRadioButtonMenuItem("Psychedelic");
         JRadioButtonMenuItem sm35=new JRadioButtonMenuItem("Smart Sky");
         JMenu menu3=new JMenu("Help");
         JMenuItem m31=new JMenuItem("Instructions");
         JMenuItem m32=new JMenuItem("About");
         int numberdisks=4;
         int numberdisksthisgame=0;
         int diskset=0;
         int backdrop=0;
         boolean isgame=false;
         int[] diskstack={-1,-1,-1};
         int[][] poledisks=new int[3][10];
         Image[] backs=new Image[5];
         Image[][] disks=new Image[3][10];
         Image[] poles=new Image[3];
         Image cloth;
         Image company;
         Image title;
         MediaTracker tracker=new MediaTracker(this);
         int[][] diskspot=new int[2][10];
         BufferedImage[][] disksr=new BufferedImage[3][10];
         Graphics2D[][] disksg=new Graphics2D[3][10];
         BufferedImage[] polesr=new BufferedImage[3];
         Graphics2D[] polesg=new Graphics2D[3];
         boolean goer=false;
         public Hanoi2(GraphicsDevice device){
         super(device.getDefaultConfiguration());
         this.device=device;
         setTitle("Tower of Hanoi");
         setDefaultCloseOperation(EXIT_ON_CLOSE);
         title=Toolkit.getDefaultToolkit().getImage("Hanoi/Title.gif");
         company=Toolkit.getDefaultToolkit().getImage("Hanoi/Company.gif");
         cloth=Toolkit.getDefaultToolkit().getImage("Hanoi/clothspread2.gif");
         poles[0]=Toolkit.getDefaultToolkit().getImage("Hanoi/woodpole1.gif");
         poles[1]=Toolkit.getDefaultToolkit().getImage("Hanoi/woodpole2.gif");
         poles[2]=Toolkit.getDefaultToolkit().getImage("Hanoi/woodpole3.gif");
         backs[0]=Toolkit.getDefaultToolkit().getImage("Hanoi/background1.gif");
         backs[1]=Toolkit.getDefaultToolkit().getImage("Hanoi/background2.gif");
         backs[2]=Toolkit.getDefaultToolkit().getImage("Hanoi/background3.gif");
         backs[3]=Toolkit.getDefaultToolkit().getImage("Hanoi/background4.gif");
         backs[4]=Toolkit.getDefaultToolkit().getImage("Hanoi/background5.gif");
         disks[0][0]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone1.gif");
         disks[0][1]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone2.gif");
         disks[0][2]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone3.gif");
         disks[0][3]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone4.gif");
         disks[0][4]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone5.gif");
         disks[0][5]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone6.gif");
         disks[0][6]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone7.gif");
         disks[0][7]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone8.gif");
         disks[0][8]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone9.gif");
         disks[0][9]=Toolkit.getDefaultToolkit().getImage("Hanoi/stone10.gif");
         disks[1][0]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass1.gif");
         disks[1][1]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass2.gif");
         disks[1][2]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass3.gif");
         disks[1][3]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass4.gif");
         disks[1][4]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass5.gif");
         disks[1][5]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass6.gif");
         disks[1][6]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass7.gif");
         disks[1][7]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass8.gif");
         disks[1][8]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass9.gif");
         disks[1][9]=Toolkit.getDefaultToolkit().getImage("Hanoi/glass10.gif");
         disks[2][0]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve1.gif");
         disks[2][1]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve2.gif");
         disks[2][2]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve3.gif");
         disks[2][3]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve4.gif");
         disks[2][4]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve5.gif");
         disks[2][5]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve6.gif");
         disks[2][6]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve7.gif");
         disks[2][7]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve8.gif");
         disks[2][8]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve9.gif");
         disks[2][9]=Toolkit.getDefaultToolkit().getImage("Hanoi/carve10.gif");
         for(int i=0; i<10; i++){
         tracker.addImage(disks[0], 0);
         tracker.addImage(disks[1][i], 0);
         tracker.addImage(disks[2][i], 0);}
         tracker.addImage(poles[0], 0);
         tracker.addImage(poles[2], 0);
         tracker.addImage(poles[1], 0);
         try{
         tracker.waitForID(0);
         }catch(Exception e){}
         tracker.addImage(title, 0);
         tracker.addImage(company, 0);
         tracker.addImage(backs[0], 0);
         tracker.addImage(backs[1], 0);
         tracker.addImage(backs[2], 0);
         tracker.addImage(backs[3], 0);
         tracker.addImage(backs[4], 0);
         tracker.addImage(cloth, 0);
         for(int i=0; i<3; i++){
         polesr[i]=new BufferedImage(11,350,BufferedImage.TYPE_INT_RGB);
         polesg[i]=polesr[i].createGraphics();}
         for(int v=0; v<3; v++){
         for(int i=0; i<10; i++){
         disksr[v][i]=new BufferedImage(65+i*15,35,BufferedImage.TYPE_INT_RGB);
         disksg[v][i]=disksr[v][i].createGraphics();
         int y=0;
         int z=-75;
         int q=0;
         for(int x=0; x<65+i*15+2; x+=2){
         if(65+i*15<81) q=7;
         if((65+i*15>80)&&(65+i*15<111)) q=6;
         if((65+i*15>110)&&(65+i*15<141)) q=4;
         if((65+i*15>140)&&(65+i*15<186)) q=3;
         if(65+i*15>185) q=2;
         if((x<(65+i*15)/8)||(x>(65+i*15)-((65+i*15)/8))) {q=q+3;}
         else if((x<(65+i*15)/4)||(x>(65+i*15)-((65+i*15)/4))) {q=q+2;}
         else if((x<(65+i*15)/3)||(x>(65+i*15)-((65+i*15)/3))) {q=q+1;}
         if(x<(65+i*15)/4) z+=q;
         if(x>=(65+i*15)/4) z-=q;
         BufferedImage bi=new BufferedImage(65+i*15,35,BufferedImage.TYPE_INT_RGB);
         BufferedImage bi2=new BufferedImage(65+i*15,35,BufferedImage.TYPE_INT_RGB);
         Graphics2D big;
         big=bi.createGraphics();
         big.drawImage(disks[v][i],0,0,this);
         RescaleOp rop = new RescaleOp(1.1f,(float)(z), null);
    rop.filter(bi,bi2);
         Rectangle2D.Double rect=new Rectangle2D.Double(65+i*15-x,0,4,35);
         disksg[v][i].setClip(rect);
         disksg[v][i].drawImage(bi2,0,0,this);}
         if((v==2)&&(i==9))
         goer=true;}}
         setJMenuBar(bar);
         bar.add(menu1);
         bar.add(menu2);
         bar.add(menu3);
         menu1.add(m11);
         menu1.add(m12);
         menu1.add(m13);
         menu1.add(m14);
         menu2.add(m21);
         menu2.add(m22);
         menu2.add(m23);
         m11.addActionListener(this);
         m12.addActionListener(this);
         m13.addActionListener(this);
         m14.addActionListener(this);
         ButtonGroup group1 = new ButtonGroup();
         m21.add(sm11);
         m21.add(sm12);
         m21.add(sm13);
         m21.add(sm14);
         m21.add(sm15);
         m21.add(sm16);
         m21.add(sm17);
         group1.add(sm11);
         group1.add(sm12);
         group1.add(sm13);
         group1.add(sm14);
         group1.add(sm15);
         group1.add(sm16);
         group1.add(sm17);
         sm11.addActionListener(this);
         sm12.addActionListener(this);
         sm13.addActionListener(this);
         sm14.addActionListener(this);
         sm15.addActionListener(this);
         sm16.addActionListener(this);
         sm17.addActionListener(this);
         ButtonGroup group2 = new ButtonGroup();
         m22.add(sm21);
         m22.add(sm22);
         m22.add(sm23);
         group2.add(sm21);
         group2.add(sm22);
         group2.add(sm23);
         sm21.addActionListener(this);
         sm22.addActionListener(this);
         sm23.addActionListener(this);
         ButtonGroup group3 = new ButtonGroup();
         m23.add(sm31);
         m23.add(sm32);
         m23.add(sm33);
         m23.add(sm34);
         m23.add(sm35);
         group3.add(sm31);
         group3.add(sm32);
         group3.add(sm33);
         group3.add(sm34);
         group3.add(sm35);
         sm31.addActionListener(this);
         sm32.addActionListener(this);
         sm33.addActionListener(this);
         sm34.addActionListener(this);
         sm35.addActionListener(this);
         menu3.add(m31);
         menu3.add(m32);
         m31.addActionListener(this);
         m32.addActionListener(this);}
         int placex=0;
         int placey=0;
         class Landscape extends JPanel{
         public void paintComponent(Graphics g){
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D) g;
         try{
         tracker.waitForAll();
         }catch (InterruptedException exc){}
         if((tracker.checkAll())&&(goer==true)){
         if(isgame==false){
         g.drawImage(title,68,75,this);
         g.drawImage(company,77,250,this);}
         if(isgame==true){
         g.drawImage(backs[backdrop],0,0,this);
         g.drawImage(cloth,0,462,this);
         g.drawImage(disks[0][0],placex,placey,this);
         for(int i=0; i<10; i++){
         g2.drawImage(disksr[diskset][i],diskspot[0][i],diskspot[1][i],this);}}}}}
         public static void main(String[] args){
         try {
    UIManager.setLookAndFeel(
    UIManager.getCrossPlatformLookAndFeelClassName());
    } catch (Exception e) { }
         GraphicsEnvironment env = GraphicsEnvironment.
    getLocalGraphicsEnvironment();
    GraphicsDevice[] devices = env.getScreenDevices();
    for (int i = 0; i < 1 /* devices.length */; i++) {
    Hanoi2 box = new Hanoi2(devices[i]);
    box.initComponents(box.getContentPane());
    box.begin();}}
         private void initComponents(Container c) {
         panel.setBackground(new java.awt.Color(201%256, 27%256, 27%256));
         panel.setPreferredSize(new Dimension(696,500));
         setContentPane(panel);}
         public void setVisible(boolean isVis) {
    super.setVisible(isVis);}
         public void begin() {
         addMouseListener(this);
         addMouseMotionListener(this);
         pack();
         setVisible(true);
         setLocationRelativeTo(null);}
         public void actionPerformed(ActionEvent e) {
         if(e.getSource()==m11){
         isgame=true;
         numberdisksthisgame=numberdisks;
         for(int i=0; i<10; i++){
         diskspot[0][i]=25+(9-i)*7;
         diskspot[1][i]=462-numberdisks*35+i*35;}
         repaint();}
    if(e.getSource()==m14){
         System.exit(0);}}
         boolean[] dragdisk={false,false,false,false,false,false,false,false,false,false};
         boolean[] istop={true,false,false,false,false,false,false,false,false,false};
         int xcheck=0;
         int ycheck=0;
         boolean dragother=false;
         int currentpole=0;
         public void mousePressed(MouseEvent e){
         int y=e.getY()-60;
         if(isgame==true){
         if((e.getX()>placex)&&(e.getX()<placex+65)&&(y>placey)&&(y<placey+35)){
         dragother=true;}
         for(int i=0; i<numberdisksthisgame; i++){
         if((e.getX()>diskspot[0][i])&&(e.getX()<diskspot[0][i]+(65+i*15))&&(y>diskspot[1][i])&&
         (y<diskspot[1][i]+35)){
         dragdisk[i]=true;
         xcheck=e.getX()-diskspot[0][i];
         ycheck=y-diskspot[1][i];}}}}
         boolean down=true;
         public void mouseDragged(MouseEvent e){
         int y=e.getY()-60;
         if(dragother==true){
         placex=e.getX();
         placey=y;
         repaint();}
         for(int i=0; i<numberdisksthisgame; i++){
         if((isgame==true)&&(dragdisk[i]==true)){
         diskspot[1][i]=y-ycheck;
         diskspot[0][i]=e.getX()-xcheck;
         repaint();}}}
         int currentpole2=0;
         int[] diskloca={25,250,475};
         public void mouseReleased(MouseEvent e){
         for(int i=0; i<numberdisksthisgame; i++){
         if(dragdisk[i]==true){
         dragdisk[i]=false;}}}
         public void mouseMoved(MouseEvent e){}
         public void mouseEntered(MouseEvent e){}
         public void mouseExited(MouseEvent e){}
         public void mouseClicked(MouseEvent e){}}

  • Best way to convert In-Memory bitmap to BufferedImage

    Hello!
    I am working with DirectShow on a Windows system to access a camera. From DirectShow I get called back on every frame with a Pointer to a native Buffer which contains a Bitmap (http://msdn.microsoft.com/en-us/library/windows/desktop/dd376985%28v=vs.85%29.aspx). To be more specific, a 24 Bit Bottom-Up Bitmap.
    The main Problem seems that the Bitmap-Format is encoded Bottom-Up and has a color order blue, green, red instead of red, green, blue. So here is my first approach, but it seems I've stumbled over a known Java-Bug (http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4723021):
    public static void main(String[] args) throws IOException {
        byte[] dataArray = new byte[] { 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1,
                -1 };
        int width = 2;
        int height = 2;
        DataBufferByte dataBuffer = new DataBufferByte(dataArray,
                dataArray.length);
        ColorSpace colorSpace = ColorSpace.getInstance(ColorSpace.CS_sRGB);
        ColorModel colorModel = new ComponentColorModel(colorSpace, new int[] {
                8, 8, 8 }, false, false, ColorModel.OPAQUE,
                dataBuffer.getDataType());
        WritableRaster raster = Raster.createInterleavedRaster(dataBuffer,
                width, height, width * 3, 3, new int[] { 2, 1, 0 }, null);
        AffineTransform tx = AffineTransform.getScaleInstance(1, -1);
        tx.translate(0, -height);
        AffineTransformOp transformOp = new AffineTransformOp(tx,
                AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
        BufferedImage image = new BufferedImage(colorModel, transformOp.filter(
                raster, null), false, null);
        ImageIO.write(image, "PNG", new File("test.png"));
    Because this example throws an Exception:
    Exception in thread "main" java.awt.image.ImagingOpException: Unable to transform src image
        at java.awt.image.AffineTransformOp.filter(Unknown Source)
        at at.test.image.ImageTest.main(ImageTest.java:36)
    The Exception is thrown because I changed the band offsets from new int[] { 0, 1, 2 } to { 2, 1, 0 }, meaning the order is blue, green, red. One approach which works is to leave the band offsets in default order (red, green blue), reverse the dataArray and then flip the image horizontally. But is this the fastest way?

    One app that comes to mind would be Graphic Converter (it's not free, but an excellent app for a multitude of things):
    http://www.lemkesoft.com/content/188/graphicconverter.html

Maybe you are looking for

  • Strange Error Message - won't let me sync

    I've been able to sync 107 of the 232 songs in my iTunes library. When I try to sync so that the other songs will appear on my iPod I get the message: "Attempting to copy to the disk 'KDESCH'S IP' failed. The disk could not be read from or written to

  • Cannot open iPhoto. Cannot open first aid photo utility.

    As per title. I tried to open the first aid photo utility as suggested by a number of people. It wouldn't open. I have tried moving my iPhoto library elsewhere. My iPhoto would ask me the location of my library. If I proceed to create a new one, iPho

  • IE9 issue with obiee 11g

    Hi All, I have done some customizations using narrative view of obiee11G which displays an image on canvas using HTML5. I can view report with the custom image using all the browsers except Internet explorer. After some research i found that i need t

  • Strange interaction with Win 7 search indexing?

    This is probably a red herring - but just in case: I am running new ACR 5.7, new DNG converter, LR 2.7, LR 3 Beta2, and Photoshop CS4 on a Dell M70 notebook with 2 Gb ram running Win 7.  I have been working on a presentation on HDR technique so I hav

  • Systemd crypttab issue

    Prior to rolling over to systemd I used the following line in my crypttab: cryptodev /dev/sdb1 /dev/sdc1:vfat:/unlockfile luks With systemd that seems to be broken, so I tried mounting the usb stick(sdc1) in fstab as /mnt/usb then mod the cryptab to: