How to convert 24bits png image into 8 bits image

Hi,
I have gone through some of threads in this forum on changing color bits. But, I still can find right way to change my image (24bits) into different color bits(8 bits). The reason i want to change the color bits because I am getting a GIF image from map server, convert it into PNG format then rescale then into size of mobile phone screen.The PNG image is really has large data length , so the it took a while to load the whole image on screen.
Note : The following code is taken from few threads in this forum and i have modified it to suit my application.
I have no idea about Java2d...any help really appreciated...Thanks in advance!!!
My code is as follow:-
public File Scale(int width, int height, BufferedImage ImgSrc)
     try
               //BufferedImage bi = ImageIO.read(ImgSrc);
               //int w = bi.getWidth(), h = bi.getHeight();
     //Image oldRescale = bi.getScaledInstance(i, j, Image.SCALE_SMOOTH);
     BufferedImage Rescale = rescale(ImgSrc, width, height);
               //ColorSpace cs = ColorSpace.getInstance(ColorSpace.CS_GRAY);
               //ColorConvertOp op = new ColorConvertOp(cs, null);
               //Rescale = op.filter(Rescale, null);
     File outfile = new File("map.png");
               ImageIO.write(Rescale, "png", outfile);
               BufferedImage fromFile = ImageIO.read(outfile);
               ColorModel cm = fromFile.getColorModel();
               System.out.println(cm.getClass() + ", bits/pixel=" + cm.getPixelSize());
          catch(Exception e)
               e.printStackTrace();
          return new File("map.png");
     public static GraphicsConfiguration getDefaultConfiguration()
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
return gd.getDefaultConfiguration();
     public static BufferedImage copyRescaled(BufferedImage tgt, BufferedImage src)
          Graphics2D g2 = tgt.createGraphics();
int w=tgt.getWidth(), h=tgt.getHeight();
hintForBestQuality(g2);
     g2.drawImage(src, 0, 0, w, h, null);
     g2.dispose();
return tgt;
public static Graphics2D hintForBestQuality(Graphics2D g2)
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
          RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.setRenderingHint(RenderingHints.KEY_RENDERING,
          RenderingHints.VALUE_RENDER_QUALITY);
return g2;
     public static BufferedImage rescale(BufferedImage src, int w, int h)
int transparency = src.getColorModel().getTransparency();
GraphicsConfiguration gc = getDefaultConfiguration();
BufferedImage tgt = gc.createCompatibleImage(w, h, transparency);
return copyRescaled(tgt, src);

First, we need to be clear about what you're trying to do -- is it rescale an
image or insure that the image is saved with a 8bit pixel depth? Or both? You are also
using GraphicsConfiguration's createCompatibleImage, which is excellent if you are going
to display the image immediately because it might be hardware accelerated
or compatible with hardware format, but you mentioned mobile phone screens, so
there is no advantage to using GraphicsConfiguration in that case, and if fact, it's
probably changing your ColorModel when you're not looking.
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.*;
import java.io.*;
import java.net.*;
import javax.imageio.*;
import javax.swing.*;
public class Example {
    public static void main(String[] args) throws IOException {
        URL url = new URL("http://java.sun.com/developer/technicalArticles/GUI/JavaServerFaces/fig2.gif");
        BufferedImage image = ImageIO.read(url);
        System.out.println("image's colormodel = " + image.getColorModel().getClass());
        BufferedImage rescaled = scaleAndConvertColorModel(image, 0.75, null); //GIF => IndexColorModel
        System.out.println("rescaled's colormodel = " + image.getColorModel().getClass());
        File png = new File("junk.png");
        ImageIO.write(rescaled, "png", png);
        BufferedImage fromFile = ImageIO.read(png);
        System.out.println("fromFile's colormodel = " + image.getColorModel().getClass());
        JPanel cp = new JPanel(new GridLayout(0,1));
        addTo(cp, image, "original image");
        addTo(cp, rescaled, "rescaled image");
        addTo(cp, fromFile, "png file image");
        JFrame f = new JFrame("Example");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setContentPane(cp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        Will rescale and convert colormodel if necessary.
        ColorModel == null => don't convert. May return src if suitable.
    public static BufferedImage scaleAndConvertColorModel(BufferedImage src, double scale, ColorModel cm) {
        int w0 = src.getWidth();
        int h0 = src.getHeight();
        int w = (int) (w0 * scale);
        int h = (int) (h0 * scale);
        ColorModel cm0 = src.getColorModel();
        if (cm == null)
            cm = cm0;
        if (w==w0 && h==h0 && cm.equals(cm0))
            return src;
        BufferedImage tgt = createImage(w, h, cm);
        Graphics2D g = tgt.createGraphics();
        if (scale < 1) {
            Image temp = src.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING);
            g.drawImage(temp, null, null);
        } else {
            hintForBestQuality(g);
            g.drawRenderedImage(src, AffineTransform.getScaleInstance(scale, scale));
        g.dispose();
        return tgt;
    public static BufferedImage createImage(int w, int h, ColorModel cm) {
        if (w <= 0 || h <= 0)
            throw new IllegalArgumentException("...");
        boolean alphaPremultiplied = cm.isAlphaPremultiplied();
        WritableRaster raster = cm.createCompatibleWritableRaster(w, h);
        return new BufferedImage(cm, raster, alphaPremultiplied, null);
    public static Graphics2D hintForBestQuality(Graphics2D g) {
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
        g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
        return g;
    static void addTo(Container c, BufferedImage image, String title) {
        JLabel label = new JLabel(new ImageIcon(image));
        label.setBorder(BorderFactory.createTitledBorder(title));
        c.add(label);
}

Similar Messages

  • How to convert output of servlet into an image????

    hi,
    guys i know how to mail and all that stuff.
    My present situation is to capture the output of a servlet as an image
    so that i can attach it as an attach it as an attachment with the mail application to forward it (also to fix it as a background to the textarea of the compose section).
    thanks in advance.

    The output of a sevrlet can be an image in the first place.
    Do you want to render an HTML output and to capture the visual representation in an image?

  • How can I save a region of an image into another image?

    How can I save a region of an image into another image? Should I use JAI?
    Java2d? Is there an example?
    Thank you.

    Here is what I try, but I find out I just get a black square for my output image, can you please tell me what am I missing?
              ImageIcon file=new ImageIcon("images/clouds.jpg"); // You can't open bmp files
                   // width, height looks correct:
                   System.out.println (" width" + file.getIconWidth());
                   System.out.println (" height" + file.getIconHeight());
                   BufferedImage bi = new BufferedImage(file.getIconWidth(), file.getIconHeight(),
                   BufferedImage.TYPE_INT_RGB);
                   int x = 0;
                   int y = 0;
                   BufferedImage subimage = bi.getSubimage(x, y, 40, 40);
                   File outputFile = new File("newimage.png");
                   ImageIO.write(subimage, "png", outputFile);

  • How to convert a PDF file into a full editable WORD file?

    Hi,
    I tried to convert a pdf file into word but it is not fully editable. I can edit the title from the main page and that's it. The rest of the word document is saved as image. I tried editing teh pdf file but that one is not working either.
    Please help on how to convert a PDF file into a full editable WORD file.
    Thank you

    Not all PDF files are created equal.  When a PDF file is created with Adobe Tools it is usually "tagged" with information about the fonts the images, the layout etc...    This way when the PDF is saved to a new format like PPT or DOC then the results are usually usable.  However, if you have a PDF file that was not tagged for some reason then run the Accessibility tools on the PDF to acquire some basic tagging.  This may get you a better result.  Also if you have a PDF that is an image, then you may want to run OCR on it.

  • How to convert a waveform signal into array of complex numbers

    How to convert a waveform signal into array of complex numbers.

    Hi Chaks,
    try this:
    (Get Waveform components, convert to complex DBL)
    Message Edited by GerdW on 01-28-2008 09:23 AM
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome
    Attachments:
    ToCDB.png ‏1 KB

  • How to convert my MM alias into an AppleID to use it with iCloud?

    I used MobileMe and created a mail that became my Apple ID. Then I created an alias that became my main e-mail so now with iCloud I wish that aslias could become my Apple ID. I don't care to loose the first Apple ID but "How to convert my MM alias into an AppleID to use it with iCloud?"

    You cannot convert an alias to Apple ID.
    You can transfer your MM to iCloud with your main Apple ID.
    There will be your alias as well.
    Regards

  • How to convert an int variable into String type

    hi everybody
    i want to know how to convert an interger variable into string variable
    i have to implement a code which goes like this
    Chioce ch;
    for(int i=0;i<32;i++)
    // here i need a code to convert the int variable i into a string variable
    ch.add(String variable);
    how do i convert that int variable i into a String type variable??
    can anyone help me?

    Different methods:
    int a;
    string s=a+"";or
    String.valueOf(int) is the better option because Int.toString() generated an intermediate object to get the endresult
    Ema

  • How to convert an NWDI project into a Local project?

    Hi Experts,
    Please tell me " how to convert an NWDI project into a Local project? "
    If you c

    Hi Srini
    1. Copy/Paste Webdynpro components in the new project as was suggested before
    2. Or create new project, copy _comp folder from old project to the new one. But, do not forget to update .dcdef & .project files manually after this. You have to set the correct project name in .dcdef and set the correct local project path in .project.
    BR, Sergei

  • How to Convert Oracle Apps Report into XML Publisher

    Hi
    How to Convert Oracle Apps Report into XML Publisher?
    Thanks

    In Brief :
    Re: XML Publisher
    In Details :
    http://www.oracle.com/technology/products/xml-publisher/docs/XMLEBSRep.pdf

  • How to convert data from rows into columns

    Hi,
    I have a sql table and the data looks like this
    GLYEAR GLMN01 GLMN02 GLMN03 GLMN04
    2007 -109712.40 6909.15 4758.72 56.88
    2007 -13411.32 19132.9 -5585.07 4362.64
    Where GLyear reprsents Year and GLMN01 is February, GLMN02 is March and so on,
    Now i want my output to be something like this which i want to insert into another table
    GLYear GLMonth GLAmount
    2007 February -109712.40
    2007 March 6909.15
    2007 April 56.88
    My new table has 3 columns, GLYear,GLMonth,GLAmount.
    Can someone please help me with the select statement on how to do this, i can work with the inserts.
    Thanks.

    I want you to check these form tread they have the same discussion as you.  They will definitely solve your problem
    http://blog.jontav.com/post/8344518585/convert-rows-to-columns-columns-to-rows-in-sql-server
    http://dba.stackexchange.com/questions/19057/convert-rows-to-columns-using-pivot-in-sql-server-when-columns-are-string-data
    http://stackoverflow.com/questions/18612326/how-to-convert-multiple-row-data-into-column-data-in-sql-server
    I hope this helps you in solving your problem. 
    Please remember to click “Mark as Answer” on the post that has answered your question as it is very relevant to other community members dealing with same problem in seeking the right answer

  • 2.....how to convert normal function module into remote enabled function mo

    Hi...
    2.....how to convert normal function module into remote enabled function module?
    thanks and regards,
    k.swaminath.

    Hi,
    In the attributes tab select radio button as  remote enabled instead of normal..
    u can call the remote enabled fm as...
    CALL FUNCTION <Function module> destination <destination name>
    Regards,
    Nagaraj

  • I can't find this anywhere... how to convert mp3 (not music) into text without spending much $$$.

    i can't find this anywhere... how to convert mp3 (not music) into text without spending much $$$.

    function(){return A.apply(null,[this].concat($A(arguments)))}
    hope1hope2 wrote:
    i can't find this anywhere... how to convert mp3 (not music) into text without spending much $$$.
    It's very unlikely that you'l
    l find any help here; this forum is used only
    for testing purposes. Unfortunately, I cannot suggest
    another forum
    Extra line breaks kindly supplied by the software.

  • How to convert trailing minus sign into the leading minus sign

    Hi
    Can any plz tell me How to convert trailing minus sign into the leading minus sign? I mean in PI the amount filed shows like 150.00- i want to convert that into -150.00.
    Thanks
    Govinda

    Hi Shabarish,
    The code works but what if the input is something like [   10.000-] i.e. with some spaces before 10.000- and the output as per your code comes as [-     10.000]. How do we tackle such cases if there is inconsistency in data i.e. some values come as [    10.000-] i.e. spaces before the number and some values as [12.000-].
    The output of this will come as
    [-    10.000]
    [-12.000]
    How to make it as
    [-10.000]
    [-12.000]
    Regards,
    Shaibayan

  • How to convert a word document into the PDF format?

    Please instruct me step by step on how to convert several Word documents into the PDF format?

    If properly installed and updated (depending on the WORD version), you can simply do any of the following:
    1. Open the doc in WORD and select Print, choose the Adobe PDF printer, print.
    2. Open the doc in WORD and go to the Acrobat menu in WORD and select create PDF (this uses PDF Maker).
    3. Open the doc in Acrobat and the conversion should be done based on PDF Maker.

  • How to convert a protected document into a PDF?

    Hello,
    I need to develop a plugin that needs to convert a protected document in office format into a pdf. I looked into the sdk and found the method AVConversionConvertToPDFWithHandler (). But can this method also apply the digital rigths of the protected document to the newly created pdf?
    Is there any other way to convert a protected document into a pdf and at the same time apply the rights to the pdf? I don't want to use Adobe LiveCycle for digital rights management.
    What are the requirements to develop a DRM plugin for acrobat?
    Please Help!
    Thanks in advance!

    The AVConversion APIs will use Office itself to perform the conversion (well, the rendering part).   I would ASSUME that when Office opens the document, it will ask for any necessary passwords or other information to determine if the user has the rights to view and/or process the content of the document.  If they do, then the conversion will succeed otherwise it will fail.   The PDF will not have any DRM applied to it, since we don't know anything about the Office DRM options.
    If you wish to apply DRM to the PDF, you will need to do that yourself or using tools such as LiveCycle Rights Management.
    From: Adobe Forums <[email protected]<mailto:[email protected]>>
    Reply-To: "[email protected]<mailto:[email protected]>" <[email protected]<mailto:[email protected]>>
    Date: Tue, 29 Nov 2011 02:26:37 -0800
    To: Leonard Rosenthol <[email protected]<mailto:[email protected]>>
    Subject: How to convert a protected document into a PDF?
    How to convert a protected document into a PDF?
    created by poortip87<http://forums.adobe.com/people/poortip87> in Acrobat SDK - View the full discussion<http://forums.adobe.com/message/4051919#4051919

Maybe you are looking for

  • HT201302 How to import photos from an ipad to a windows 8 pc????

    i am trying to transfer my photos from my ipad to my pc, i am using windows 8. There is no autoplay pop up available and the ipad does not come up in the computer folder. please help its really frustrating.

  • Help! How do I create a document with an imported PDF in 300dpi using a FOGRA27 colour profile?

    I am a new Indesign user and I have been working with GIMP for the last year creating single colour print-ready PDFs. But now I need to create a document with a FOGRA27 CMYK colour profile and a resolution of at least How do I create a document with

  • Idoc to FCC error.

    HI, Scenario is Idoc to File scenario using BPM, needs to drop the file using FCC and BPM collect messages is used All the fields are populating successfully but facing issues with serial number and date fields, 1. With respect to Serial Number: from

  • Unknown File type for QFX with VMWare/Quicken

    I have quicken loaded in VMWare and want to open Quicken from my iMac when double clicking on the quicken QFX file.  I get an error msg "Unknown File type"

  • [request] Reiser4-patched GRUB

    ... Because I can't copy and paste under Minimax, LILO is screwing up like there's no tomorrow, and Damn Small Linux can't handle Reiser4. Also, I think it might be nicer to potential Reiser4/GRUB users to have the PKGBUILD and other necessary files