Need to convert byte[] to image

hi frnds,
i have a byte[](which i got it from an image) i need to convert back to image.Could u pls suggest me how to??
i tried with Pixelgrabber but i exaclty did get wht shld be the input for it(tried giving image file name). :(
So pls let me know how and wht to use..ASAP.
Regards
subinjava

Subinjava wrote:
..i have a byte[](which i got it from an image) i need to convert back to image.Could u pls suggest me how to??
Image image = Toolkit.getDefaultToolkit().createImage(byteArray)See http://java.sun.com/javase/6/docs/api/java/awt/Toolkit.html#createImage(byte[]) for more details.

Similar Messages

  • Help needed on convert JTable to Image

    Hi, all
    I have made an application that can output a JTable with different colours in its every cells. Now I want to select the whole Table and put it as an Image to one of the Image Viewer Softwares(e.g. windows picture viewer).
    Is there anyone knows how to do that?
    Thanks in advance!
    Regards,
    swat.

    Now I want to select the whole Table and put it as an
    Image to one of the Image Viewer Softwares(e.g.
    windows picture viewer). If you don't have to do it programmatically, and you are working on windows, select the window with the table, Alt-PrtScr will copy just that window into the clipboard, and you can paste it into many different apps, including image views, word, so on.

  • Converting a PNG image to an array of bytes and vice versa..

    hi all,
    i need to convert a PNG image to an array of bytes ,then converting back this array of bytes to The PNG image again ,i read this can be done using output streams but i feel like a dump and i can't fix the whole thingy out ! ,can anybody help me in this ,by explaining how can this be established????
    Regards,
    D.Roth

    hi all,
    i need to convert a PNG image to an array of bytes ,then converting back this array of bytes to The PNG image again ,i read this can be done using output streams but i feel like a dump and i can't fix the whole thingy out ! ,can anybody help me in this ,by explaining how can this be established????
    Regards,
    D.Roth

  • Converting byte[] to unicode , help needed.

    need help, folks.
    i need to convert byte[] to unicode in byte[] form
    say i already loaded bunch of data
    byte[] bytes = {........} //bunch array of bytesand i read in the bytes as a stream in the native form.
    ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
    InputStreamReader isr = new InputStreamReader(stream,"GB18030");how do i get the bytes back in unicode ? i've been trying all kinds of methods, but doesnt seems to get what i want. i'm novice programmer, someone pls guide me ? thx.

                String s ;
              StringBuffer buffer = new StringBuffer();
              try {
                   ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
                   InputStreamReader isr = new InputStreamReader(stream, "GB18030");
                   Reader in = new BufferedReader(isr);
                   int ch;
                   while ((ch = in.read()) > -1) {
                   buffer.append((char)ch);
                   in.close();
                   s = buffer.toString();
                   bytes = s.getBytes("UnicodeLittle");
                   out.write(bytes);
              } catch (IOException e) {
                   e.printStackTrace();
                   //return null;
              }ah, nvm, i found a better solution to it, i'm little confused before this. the code above works fine.
    well, thx alot.

  • Need conversion mechanism for converting 24 bit image to 16 bit

    In my java project I need to convert 24 bit image to 16 bit image. I don't have any clue. Please provide me the option to implement it.
    Thanks,
    jai

    That doesn't tell me much, and I know what you're talking about. I doubt that it tells the OP anything useful whatsoever.Sorry EJP, it was a mouthful I know. Maybe this will help instead, a ColorConversionOps class to work on *32 bit > 16 bit > 32 bit colors*. To help clarify where the 16 bit color input and output goes, some of the methods return or require parameters of type short. Also take notice the bitmask for variables of type short vs the bitmasks for int. AND pay particular attention to the unsigned right bit-shifting of the most-significant-digit.
    public class ColorConversionOps
      public static short convert32_16(int rgb) {
        int a = ((rgb & 0xF0000000) >>> 16);
        int r = ((rgb & 0x00F00000) >>  12);
        int g = ((rgb & 0x0000F000) >>   8);
        int b = ((rgb & 0x000000F0) >>   4);
        return (short)( a | r | g | b);
      public static int convert16_32(short rgb) {
        int a = ((rgb & 0xF000) << 16);
        int r = ((rgb & 0x0F00) << 12);
        int g = ((rgb & 0x00F0) <<  8);
        int b = ((rgb & 0x000F) <<  4);
        return (a | r | g | b);
      public static void printRGB_32(int rgb) {
        System.out.println("a="+((rgb & 0xFF000000) >>> 24));
        System.out.println("r="+((rgb & 0x00FF0000) >>  16));
        System.out.println("g="+((rgb & 0x0000FF00) >>  8));
        System.out.println("b="+ (rgb & 0x000000FF));
        System.out.println();
      public static void printRGB_16(short rgb) {
        System.out.println("a="+((rgb & 0xF000) >>> 12));
        System.out.println("r="+((rgb & 0x0F00) >>  8));
        System.out.println("g="+((rgb & 0x00F0) >>  4));
        System.out.println("b="+ (rgb & 0x000F));
        System.out.println();
    }Now to make the conversion from 32 bit color to 16 bit color and back. NOTICE there willl be a loss of precision -- just like someone else has already said.
    public class Test
      public static void main(String[] args)
        int rgb = 0xFFFFFFFF;
        ColorConversionOps.printRGB_32(rgb);
        //a=255
        //r=255
        //g=255
        //b=255
        rgb = ColorConversionOps.convert32_16(rgb);
        ColorConversionOps.printRGB_16((short)rgb);
        //a=15
        //r=15
        //g=15
        //b=15
        rgb = ColorConversionOps.convert16_32((short)rgb);
        ColorConversionOps.printRGB_32(rgb);
        //a=240
        //r=240
        //g=240
        //b=240
    }And now we see, the reason 16bit color is so unpopular to the rest of the world, but not for us here!

  • Bytes to image at server

    Hi
    I am doing client server application which send image from client to server...
    i am able to send image bytes from client to server ..But at server I am not able to display image which i sent from client.............
    Can you guys plz tell how i can convert bytes to image at Servlet server.....
    Thanks in advance...

    DragEvent has property called dragInitiator. That might help.
    Otherwise, you can add mouseDown event listener to your
    TileList and in that handler do something like:
    var initiator:UIComponent = UIComponent(event.currentTarget);
    and then add any effects to the initiator.
    ATTA

  • To convert an rgb image to 8 bit grayscale

    Hey,
    I need to convert an rgb image to 8 bit grayscale image as the image is being acquired, im using the imaq create VI, which has an 'image type' terminal which allows the choice of image to be selected.however this isnt working. any solutions?
    also
    Im trying to make a image constant for the imaq subtraction VI, so the this constant image is subtracted from each image as its acquired.what would be the easiest way of doing this, without having the user specify the same image path each time? thanks.

    Not sure what you mean by extracting a plane?
    Here is a VI that will convert an image to 8-Bit.  This paired with the grayscale one will get the desired result.  See example.vi below.  Order that they are applied does give slightly different results.
    LV 8.0 through 2013, Win 7
    CLA
    Attachments:
    example.vi ‏12 KB
    QSI Convert to 8-Bit Image.vi ‏22 KB
    QSI Grayscale Image.vi ‏28 KB

  • Need to convert an image to .jpeg using Java !

    Hello,
    i am working in images now. i need to convert any image in the form of .jpeg using Java. in other words, i need to store an image in the form of .jpeg format. can any of u help me ! thanks in advance.
    - Krishna

    There's also jimi, at http://java.sun.com/products/jimi/
    You can do something like:
    image = new BufferedImage (width, height, BufferedImage.TYPE_INT_RGB);
    // create your image
    String path = "/path/image.jpg";
    Jimi.putImage(image, path);
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • I Just converted my iPhoto library to Photos. Now I can't find my RAW files. I need to have all the images in my old library show up in their RAW format.

    I Just converted my iPhoto library to Photos. Now I can't find my RAW files. I need to have all the images in my old library show up in their RAW format.

    Unfortunately no - Photos use extensions and the vendor (adobe) will have to implement the extension to allow external edits in PS or PSE
    For now you must export the photo, edit and then import - not great but a work arond
    And you can continue to use iPhoto until Photos meets your needs - launch it in your applications folder - if you need assistance on this see Why won't my iPhotos open?
    LN

  • 'greyscale' RGB image, need to convert to specific CMYK black...  how?

    Hi,
    I have an image provided in RGB, but visually it's greyscale, except for some red areas on certain clothing. I need to convert it to CMYK, and I want all the black areas to be 40/30/20/100, and the grey values should be percentages of this mix. The red should be visually unaltered. Im using CS3 btw.
    Is there a way to quickly do this? I can convert to a generic CMYK value then tweak the curves of each channel, but it will affect the red. I could make a selection to exclude the red, but i feel there must be a way for me to define my black, and convert, and for my wishes to be granted automagically.
    I tried redefining my default black in the foreground/background swatches, but that had no effect on the subsequent conversion.
    Also, I'm trying to avoid profiles as my brain is foggy in that area...
    Thank you,
    Simon Gregory

    Without seeing the image, it might be a shot in the dark, but what about creating a new CYMK document, of the same size as the RGB one. Add a layer filled with the 40/30/20/100 black.
    Go to the RGB image, In the Channels panel, drag the red channel to the new channel icon. Drag this new channel to the CYMK channel panel. Add a layer mask to the 40/30... layer. go back to the channels panel, and target only the copied channel, copy it, target the layer mask channel, paste. Target the Layer mask, invert it.
    Now, select and bring the red part from the RGB image, and you should be good to go...

  • Convert byte array to table of int

    [http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print|http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print] Hello friends.
    I'm pretty new with PL/SQL.
    I have code that run well on MSSQL and I want to convert it to PL/SQL with no luck.
    The code converts byte array to table of int.
    The byte array is actually array of int that was converted to bytes in C# for sending it as parameter.
    The TSQL code is:
    CREATE FUNCTION dbo.GetTableVarchar(@Data image)
    RETURNS @DataTable TABLE (RowID int primary key IDENTITY ,
    Value Varchar(8000))
    AS
    BEGIN
    --First Test the data is of type Varchar.
    IF(dbo.ValidateExpectedType(103, @Data)<>1) RETURN
    --Loop thru the list inserting each
    -- item into the variable table.
    DECLARE @Ptr int, @Length int,
    @VarcharLength smallint, @Value Varchar(8000)
    SELECT @Length = DataLength(@Data), @Ptr = 2
    WHILE(@Ptr<@Length)
    BEGIN
    --The first 2 bytes of each item is the length of the
    --varchar, a negative number designates a null value.
    SET @VarcharLength = SUBSTRING(@Data, @ptr, 2)
    SET @Ptr = @Ptr + 2
    IF(@VarcharLength<0)
    SET @Value = NULL
    ELSE
    BEGIN
    SET @Value = SUBSTRING(@Data, @ptr, @VarcharLength)
    SET @Ptr = @Ptr + @VarcharLength
    END
    INSERT INTO @DataTable (Value) VALUES(@Value)
    END
    RETURN
    END
    It's taken from http://www.codeproject.com/KB/database/PassingArraysIntoSPs.aspx?display=Print.
    The C# code is:
    public byte[] Convert2Bytes(int[] list)
    if (list == null || list.Length == 0)
    return new byte[0];
    byte[] data = new byte[list.Length * 4];
    int k = 0;
    for (int i = 0; i < list.Length; i++)
    byte[] intBytes = BitConverter.GetBytes(list);
    for (int j = intBytes.Length - 1; j >= 0; j--)
    data[k++] = intBytes[j];
    return data;
    I tryied to convert the TSQL code to PL/SQL and thats what I've got:
    FUNCTION GetTableInt(p_Data blob)
    RETURN t_array --t_array is table of int
    AS
    l_Ptr number;
    l_Length number;
    l_ID number;
    l_data t_array;
    BEGIN
         l_Length := dbms_lob.getlength(p_Data);
    l_Ptr := 1;
         WHILE(l_Ptr<=l_Length)
         loop
              l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
              IF(l_ID<-2147483646)THEN
                   IF(l_ID=-2147483648)THEN
                        l_ID := NULL;
                   ELSE
                        l_Ptr := l_Ptr + 4;
                        l_ID := to_number( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
                   END IF;
                   END IF;
    l_data(l_data.count) := l_ID;
              l_Ptr := l_Ptr + 4;
         END loop;
         RETURN l_data;
    END GetTableInt;
    This isn't work.
    This is the error:
    Error report:
    ORA-06502: PL/SQL: numeric or value error: character to number conversion error
    06502. 00000 - "PL/SQL: numeric or value error%s"
    I think the problem is in this line:
    l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
    but I don't know how to fix that.
    Thanks,
    MTs.

    I'd found the solution.
    I need to write:
    l_ID := utl_raw.cast_to_binary_integer( DBMS_LOB.SUBSTR(p_Data, 4,l_ptr));
    instead of:
    l_ID := to_number( DBMS_LOB.SUBSTR (p_Data, 4, l_ptr));
    The performance isn't good, it's take 2.8 sec to convert 5000 int, but it's works.

  • Converting bytes to pixels???

    Hi Everyone,
    My Jdev version is 11.1.2.3.0.
    I have deloped one ADF applicaton which is working fine.
    Now i have added a table to the page which has 3 columns. The width of the column in ADF page should be equal to width of the column in the database.
    How can i convert bytes to pixels in my ADF page.
    The three column's width in database are: 200Bytes, 250Bytes, 150Bytes. Now i need to specify the width in pixels in ADF.
    how can i do that?
    Any ways to do that?
    Thanks.

    Yeah I meant e[i] - sorry about that.
    When you say "diagram the to / from arrays" do you mean you want to see their definition & initialisation? If so, please see below:
    numBands, length & width are the three fields read in from the image header.
    byte[] imageDataByte = new byte[numBands * length * width];
              ra.read(imageDataByte,0,numBands * length * width);
              int[] iD = new int[numBands * length * width];
              int count = 0;     
              int[] imageData = new int[numBands * length * width];
              for (int x = 0; x < length; x++)
              for (int y = 0; y < numBands; y++)
              for (int z = 0; z < width; z++)
                   imageData[(length*z+x) + (length* width*y)] += imageDataByte[(length*z+x) + (length* width*y)] << ((length*z+x) + (length* width*y)*512);     
                   count = count + 1;
                   System.out.println(count + ": " + imageData[(length*z+x) + (length* width*y)]);
    Any help would be greatly appreciated.
    Many thanks,
    CG.

  • Converting cmyk compressed images to rgb compressed format

    Hi,
    I need some help in converting of CMYK images to RGB images. I got some sample code from internet but I get some run time exceptions with that and I'm not able to figure out the reason for the same. Pls help me in fixing the same. Any help will be sincerely appreicated.
    The code is given below :
    import java.awt.image.*;
    import java.awt.image.renderable.*;
    import java.awt.color.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    import javax.media.jai.*;
    import com.sun.image.codec.jpeg.*;
    public class CMYKTest1 {
      public static void main(String args[]) throws Exception{
         RenderedOp op = JAI.create("fileload", "Kristopher Brock LOGO.jpg");
         ColorModel rgbcm = op.getColorModel();
         ICC_Profile profile = ICC_Profile.getInstance("CMYK.pf");
    //     ICC_Profile profile = ICC_Profile.getInstance(ColorSpace.TYPE_CMYK);
         ICC_ColorSpace icp = new ICC_ColorSpace(profile);
         ColorModel colorModel =
              RasterFactory.createComponentColorModel(op.getSampleModel().getDataType(),
                                                                icp,
                                                                false,
                                                                false,
                                                                Transparency.OPAQUE);
         ImageLayout il = new ImageLayout();
         il.setSampleModel(colorModel.createCompatibleSampleModel(op.getWidth(),
                                                                                op.getHeight()));
         RenderingHints hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, il);
         ParameterBlock pb = new ParameterBlock();
         pb.addSource(op).add(colorModel);
         op = JAI.create("ColorConvert", pb, hints);
         pb = new ParameterBlock();
         pb.addSource(op).add(rgbcm);
         il = new ImageLayout();
         il.setSampleModel(rgbcm.createCompatibleSampleModel(op.getWidth(),
                                                                          op.getHeight()));
         hints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, il);
         op = JAI.create("ColorConvert", pb, hints);
         JAI.create("filestore", op, "earthrgb.jpg", "JPEG", null);
         BufferedImage img = op.getAsBufferedImage(null, null);
         OutputStream fout = new FileOutputStream("earthrgb1.jpg");
         JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fout);
         JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
         param.setQuality(1, false);
         param.setXDensity(300);
         param.setYDensity(400);
         encoder.encode(img, param);
         fout.close();
    }I get the following error:
    Caused by: java.lang.IllegalArgumentException: Numbers of source Raster bands and source color space components do not match
         at java.awt.image.ColorConvertOp.filter(Unknown Source)
         at com.sun.media.jai.opimage.ColorConvertOpImage.computeRectNonColorSpaceJAI(ColorConvertOpImage.java:373)
         at com.sun.media.jai.opimage.ColorConvertOpImage.computeRect(ColorConvertOpImage.java:290)
         at javax.media.jai.PointOpImage.computeTile(PointOpImage.java:914)
         at com.sun.media.jai.util.SunTileScheduler.scheduleTile(SunTileScheduler.java:904)
         at javax.media.jai.OpImage.getTile(OpImage.java:1129)
         at javax.media.jai.PointOpImage.computeTile(PointOpImage.java:911)
         at com.sun.media.jai.util.SunTileScheduler.scheduleTile(SunTileScheduler.java:904)
         at javax.media.jai.OpImage.getTile(OpImage.java:1129)
         at com.sun.media.jai.codecimpl.JPEGImageEncoder.encode(JPEGImageEncoder.java:173)
         at com.sun.media.jai.opimage.EncodeRIF.create(EncodeRIF.java:70)
         ... 24 more
    Error: One factory fails for the operation "filestore"
    Occurs in: javax.media.jai.ThreadSafeOperationRegistry
    java.lang.reflect.InvocationTargetException
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
         at java.lang.reflect.Method.invoke(Unknown Source)
         at javax.media.jai.FactoryCache.invoke(FactoryCache.java:122)
         at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1674)
         at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:473)
         at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:332)
         at javax.media.jai.RenderedOp.createInstance(RenderedOp.java:819)
         at javax.media.jai.RenderedOp.createRendering(RenderedOp.java:867)
         at javax.media.jai.RenderedOp.getRendering(RenderedOp.java:888)
         at javax.media.jai.JAI.createNS(JAI.java:1099)
         at javax.media.jai.JAI.create(JAI.java:973)
         at javax.media.jai.JAI.create(JAI.java:1668)
         at CMYKTest1.main(CMYKTest1.java:79)
    Caused by: javax.media.jai.util.ImagingException: All factories fail for the operation "encode"
         at javax.media.jai.OperationRegistry.invokeFactory(OperationRegistry.java:1687)
         at javax.media.jai.ThreadSafeOperationRegistry.invokeFactory(ThreadSafeOperationRegistry.java:473)
         at javax.media.jai.registry.RIFRegistry.create(RIFRegistry.java:332)
         at com.sun.media.jai.opimage.FileStoreRIF.create(FileStoreRIF.java:138)
         ... 15 moreThanks & Regards,
    Magesh.

    The following code converts an cmyk jpeg image into an rgb jpeg image.
    The only problem if this code is that it loads the whole image in memory and thus you'll need a lot of RAM when converting large images. For example, it take around 300 MB to convert a 3000*3800px image (this is a 5MB jpeg image when compressed on disk).
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import javax.imageio.ImageIO;
    import javax.imageio.ImageReader;
    import javax.imageio.stream.ImageInputStream;
    import javax.imageio.metadata.IIOMetadata;
    import javax.imageio.metadata.IIOMetadataNode;
    import java.util.*;
    import java.io.*;
    import java.awt.image.*;
    import java.awt.*;
    import java.awt.color.ColorSpace;
    import org.w3c.dom.NodeList;
    public class Test {
        public static void main(String[] args) throws Exception {
            BufferedImage i1 = readImage(new File("cmyk.jpg"));
            BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File("rgb.jpg")));
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(i1);
            param.setQuality(1, false);
            encoder.setJPEGEncodeParam(param);
            encoder.encode(i1);
        public Test() {
        // extract metadata
        public static BufferedImage readImage(File file) throws IOException {
            // Get an ImageReader.
            ImageInputStream input = ImageIO.createImageInputStream(file);
            Iterator readers = ImageIO.getImageReaders(input);
            if (readers == null || !readers.hasNext()) {
                throw new RuntimeException("No ImageReaders found");
            ImageReader reader = (ImageReader) readers.next();
            reader.setInput(input);
            String format = reader.getFormatName();
            if ("JPEG".equalsIgnoreCase(format) || "JPG".equalsIgnoreCase(format)) {
                IIOMetadata metadata = reader.getImageMetadata(0);
                String metadataFormat = metadata.getNativeMetadataFormatName();
                IIOMetadataNode iioNode = (IIOMetadataNode) metadata.getAsTree(metadataFormat);
                NodeList children = iioNode.getElementsByTagName("app14Adobe");
                if (children.getLength() > 0) {
                    iioNode = (IIOMetadataNode) children.item(0);
                    int transform = Integer.parseInt(iioNode.getAttribute("transform"));
                    Raster raster = reader.readRaster(0, reader.getDefaultReadParam());
                    if (input != null) {
                        input.close();
                    reader.dispose();
                    return createJPEG4(raster, transform);
            throw new RuntimeException("No ImageReaders found");
         * Java's ImageIO can't process 4-component
         * images
         * <p/>
         * and Java2D can't apply AffineTransformOp
         * either,
         * <p/>
         * so convert raster data to
         * RGB.
         * <p/>
         * Technique due to MArk
         * Stephens.
         * <p/>
         * Free for any
         * use.
        private static BufferedImage createJPEG4(Raster raster, int xform) {
            int w = raster.getWidth();
            int h = raster.getHeight();
            byte[] rgb = new byte[w * h * 3];
            // if (Adobe_APP14 and transform==2) then YCCK else CMYK
            if (xform == 2) {    // YCCK -- Adobe
                float[] Y = raster.getSamples(0, 0, w, h, 0, (float[]) null);
                float[] Cb = raster.getSamples(0, 0, w, h, 1, (float[]) null);
                float[] Cr = raster.getSamples(0, 0, w, h, 2, (float[]) null);
                float[] K = raster.getSamples(0, 0, w, h, 3, (float[]) null);
                for (int i = 0, imax = Y.length, base = 0; i < imax; i++, base += 3) {
                    float k = 220 - K, y = 255 - Y[i], cb = 255 - Cb[i], cr = 255 - Cr[i];
    double val = y + 1.402 * (cr - 128) - k;
    val = (val - 128) * .65f + 128;
    rgb[base] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
    val = y - 0.34414 * (cb - 128) - 0.71414 * (cr - 128) - k;
    val = (val - 128) * .65f + 128;
    rgb[base + 1] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
    val = y + 1.772 * (cb - 128) - k;
    val = (val - 128) * .65f + 128;
    rgb[base + 2] = val < 0.0 ? (byte) 0 : val > 255.0 ? (byte) 0xff : (byte) (val + 0.5);
    else {
    // assert xform==0: xform;
    // CMYK
    int[] C = raster.getSamples(0, 0, w, h, 0, (int[]) null);
    int[] M = raster.getSamples(0, 0, w, h, 1, (int[]) null);
    int[] Y = raster.getSamples(0, 0, w, h, 2, (int[]) null);
    int[] K = raster.getSamples(0, 0, w, h, 3, (int[]) null);
    for (int i = 0, imax = C.length, base = 0; i < imax; i++, base += 3) {
    int c = 255 - C[i];
    int m = 255 - M[i];
    int y = 255 - Y[i];
    int k = 255 - K[i];
    float kk = k / 255f;
    rgb[base] = (byte) (255 - Math.min(255f, c * kk + k));
    rgb[base + 1] = (byte) (255 - Math.min(255f, m * kk + k));
    rgb[base + 2] = (byte) (255 - Math.min(255f, y * kk + k));
    // from other image types we know InterleavedRaster's can be
    // manipulated by AffineTransformOp, so create one of
    // those.
    raster = Raster.createInterleavedRaster(new DataBufferByte(rgb, rgb.length), w, h, w * 3, 3, new int[]{0, 1, 2}, null);
    ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_sRGB);
    ColorModel cm = new ComponentColorModel(cs, false, true, Transparency.OPAQUE, DataBuffer.TYPE_BYTE);
    return new BufferedImage(cm, (WritableRaster) raster, true, null);

  • Converting string to image

    hi all
    i m facing a problem while converting a string in to an image.
    Here is my code......
    String s=new String(" Report ");
    byte []raw=s.getBytes();
    Image image = Image.createImage(raw, 0, raw.length);
    but it is not creating an image....
    but if we use the returning byte[] of the getSnapshot() method then it will create an image......why this happens...
    how can i covert my string into an image???????plz help
    ritwik

    I need to convert a string to an image, I went throuth the topics in Sun forums but it's still not crear!!!
    Please give a sample code to solve the simple task:
    convert the string to an image (no applet) off-screen so that this image can be downloaded later !
    I try to do this (as advised by some one on this forum)
    BufferedImage bi = new BufferedImage(100, 100, 1);
    Graphics2D g = bi.createGraphics();
    g.drawString("test", 80, 80);
    ImageWriter iw = ImageIO.getImageWriter(imageReader R);
    iw.setOutput(new FileImageOutputStream(File outputFile));
    iw.write(bi);
    but only first row works , the rest couses exeptions!!!

  • Need to convert JApplet to JFrame

    I need to write code for where I have 60 balls bouncing around inside a window. The client will then be able to select a button and it will pull out a ball with the number 1-60 written on it. The user will be able to do this up to 7 times. Each time it is done the past numbers that have already appeared can not reappear. What I am stuck on right now is geting my balls into a JFrame. Can anyone give advice or show how to. I currently have my 60 balls running in a JApplet. Here is the JAVA code and the HTML code. Thanks!
    Here is the JAVA code
    import java.awt.*;
    import java.applet.*;
    import java.util.*;
    import javax.swing.*;
    class CollideBall{
    int width, height;
    public static final int diameter=20;
    //coordinates and value of increment
    double x, y, xinc, yinc, coll_x, coll_y;
    boolean collide;
    Color color;
    Graphics g;
    Rectangle r;
    //the constructor
    public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c){
    width=w;
    height=h;
    this.x=x;
    this.y=y;
    this.xinc=xinc;
    this.yinc=yinc;
    color=c;
    r=new Rectangle(150,80,130,90);
    public double getCenterX() {return x+diameter/2;}
    public double getCenterY() {return y+diameter/2;}
    public void alterRect(int x, int y, int w, int h){
    r.setLocation(x,y);
    r.setSize(w,h);
    public void move(){
    if (collide){  
    double xvect=coll_x-getCenterX();
    double yvect=coll_y-getCenterY();
    if((xinc>0 && xvect>0) || (xinc<0 && xvect<0))
    xinc=-xinc;
    if((yinc>0 && yvect>0) || (yinc<0 && yvect<0))
    yinc=-yinc;
    collide=false;
    x+=xinc;
    y+=yinc;
    //when the ball bumps against a boundary, it bounces off
    if(x<6 || x>width-diameter){
    xinc=-xinc;
    x+=xinc;
    if(y<6 || y>height-diameter){
    yinc=-yinc;
    y+=yinc;
    //cast ball coordinates to integers
    int x=(int)this.x;
    int y=(int)this.y;
    //bounce off the obstacle
    //left border
    if(x>r.x-diameter&&x<r.x-diameter+7&&xinc>0&&y>r.y-diameter&&y<r.y+r.height){
    xinc=-xinc;
    x+=xinc;
    //right border
    if(x<r.x+r.width&&x>r.x+r.width-7&&xinc<0&&y>r.y-diameter&&y<r.y+r.height){
    xinc=-xinc;
    x+=xinc;
    //upper border
    if(y>r.y-diameter&&y<r.y-diameter+7&&yinc>0&&x>r.x-diameter&&x<r.x+r.width){
    yinc=-yinc;
    y+=yinc;
    //bottom border
    if(y<r.y+r.height&&y>r.y+r.height-7&&yinc<0&&x>r.x-diameter&&x<r.x+r.width){
    yinc=-yinc;
    y+=yinc;
    public void hit(CollideBall b){
    if(!collide){
    coll_x=b.getCenterX();
    coll_y=b.getCenterY();
    collide=true;
    public void paint(Graphics gr){
    g=gr;
    g.setColor(color);
    //the coordinates in fillOval have to be int, so we cast
    //explicitly from double to int
    g.fillOval((int)x,(int)y,diameter,diameter);
    g.setColor(Color.white);
    g.drawArc((int)x,(int)y,diameter,diameter,45,180);
    g.setColor(Color.darkGray);
    g.drawArc((int)x,(int)y,diameter,diameter,225,180);
    public class BouncingBalls extends Applet implements Runnable {
    Thread runner;
    Image Buffer;
    Graphics gBuffer;
    CollideBall ball[];
    //Obstacle o;
    //how many balls?
    static final int MAX=60;
    boolean intro=true,drag,shiftW,shiftN,shiftE,shiftS;
    boolean shiftNW,shiftSW,shiftNE,shiftSE;
    int xtemp,ytemp,startx,starty;
    int west, north, east, south;
    public void init() {  
    Buffer=createImage(getSize().width,getSize().height);
    gBuffer=Buffer.getGraphics();
    ball=new CollideBall[MAX];
    int w=getSize().width-5;
    int h=getSize().height-5;
    //our balls have different start coordinates, increment values
    //(speed, direction) and colors
    for (int i = 0;i<60;i++){
    ball=new CollideBall(w,h,50+i,20+i,1.5,2.0,Color.white);
    /* ball[1]=new CollideBall(w,h,60,210,2.0,-3.0,Color.red);
    ball[2]=new CollideBall(w,h,15,70,-2.0,-2.5,Color.pink);
    ball[3]=new CollideBall(w,h,150,30,-2.7,-2.0,Color.cyan);
    ball[4]=new CollideBall(w,h,210,30,2.2,-3.5,Color.magenta);
    ball[5]=new CollideBall(w,h,360,170,2.2,-1.5,Color.yellow);
    ball[6]=new CollideBall(w,h,210,180,-1.2,-2.5,Color.blue);
    ball[7]=new CollideBall(w,h,330,30,-2.2,-1.8,Color.green);
    ball[8]=new CollideBall(w,h,180,220,-2.2,-1.8,Color.black);
    ball[9]=new CollideBall(w,h,330,130,-2.2,-1.8,Color.gray);
    ball[10]=new CollideBall(w,h,330,10,-2.1,-2.0,Color.gray);
    ball[11]=new CollideBall(w,h,220,230,-1.2,-1.8,Color.gray);
    ball[12]=new CollideBall(w,h,230,60,-2.3,-2.5,Color.gray);
    ball[13]=new CollideBall(w,h,320,230,-2.2,-1.8,Color.gray);
    ball[14]=new CollideBall(w,h,130,300,-2.7,-3.0,Color.gray);
    ball[15]=new CollideBall(w,h,210,90,-2.0,-1.8,Color.gray);*/
    public void start(){
    if (runner == null) {
    runner = new Thread (this);
    runner.start();
    /* public void stop(){
    if (runner != null) {
    runner.stop();
    runner = null;
    public void run(){
    while(true) {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    try {runner.sleep(15);}
    catch (Exception e) { }
    //move our balls around
    for(int i=0;i<MAX;i++)
    ball[i].move();
    handleCollision();
    repaint();
    boolean collide(CollideBall b1, CollideBall b2){
    double wx=b1.getCenterX()-b2.getCenterX();
    double wy=b1.getCenterY()-b2.getCenterY();
    //we calculate the distance between the centers two
    //colliding balls (theorem of Pythagoras)
    double distance=Math.sqrt(wx*wx+wy*wy);
    if(distance<b1.diameter)
    return true;
    return false;
    private void handleCollision()
    //we iterate through all the balls, checking for collision
    for(int i=0;i<MAX;i++)
    for(int j=0;j<MAX;j++)
    if(i!=j)
    if(collide(ball[i], ball[j]))
    ball[i].hit(ball[j]);
    ball[j].hit(ball[i]);
    public void update(Graphics g)
    paint(g);
    public void paint(Graphics g)
    gBuffer.setColor(Color.lightGray);
    gBuffer.fillRect(0,0,getSize().width,getSize().height);
    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
    //paint our balls
    for(int i=0;i<MAX;i++)
    ball[i].paint(gBuffer);
    g.drawImage (Buffer,0,0, this);
    Here is the HTML code
    <html>
    <body bgcolor="gray">
    <br><br>
    <div align="center">
    <applet code="BouncingBalls.class" width="1000" height="650"></applet>
    </div>
    </body>
    </html>

    In the future, Swing related questions should be posted in the Swing forum.
    First you need to convert your custom painting. This is done by overriding the paintComponent() method of JComponent or JPanel. Read the Swing tutorial on [Custom Painting|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html].
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.
    Don't forget to use the [Code Formatting Tags|http://forum.java.sun.com/help.jspa?sec=formatting], so the posted code retains its original formatting.

Maybe you are looking for