Having problem saving an iamge into a BMP file, please help!

I'm writing a class to read an BMP image and output it again into another BMP file.
After searching on the forum i have found some code for reading and writing bmp files, i put them togather to make up this class, however, the output bmp file is not correct, can anyone look at my code and tell me wots wrong? thanks!
public class BMP {
byte bf[]=new byte[14];
//     private byte bitmapFileHeader [] = new byte [14];
byte bi[]=new byte[40];
     public Image BMPReader(String filePath){
          Image image = null;
     try{
     FileInputStream fs=new FileInputStream(filePath);
     fs.read(bf,0,14); //Reads the 14byte fileheader      
     fs.read(bi,0,40); //reads the 40byte infoheader
     int nwidth=(((int)bi[7]&0xff)<<24) //pic width
     | (((int)bi[6]&0xff)<<16)
     | (((int)bi[5]&0xff)<<8)
     | (int)bi[4]&0xff;
     int nheight=(((int)bi[11]&0xff)<<24) //pic height
     | (((int)bi[10]&0xff)<<16)
     | (((int)bi[9]&0xff)<<8)
     | (int)bi[8]&0xff;
     int nbitcount=(((int)bi[15]&0xff)<<8) | (int)bi[14]&0xff;
     //pic size
     int nsizeimage=(((int)bi[23]&0xff)<<24)
     | (((int)bi[22]&0xff)<<16)
     | (((int)bi[21]&0xff)<<8)
     | (int)bi[20]&0xff;
     //parse 24bit bmp
     if(nbitcount==24){
     int npad=(nsizeimage/nheight)-nwidth*3;
     int ndata[]=new int[nheight*nwidth];
     byte brgb[]=new byte[(nwidth+npad)*3*nheight];
     fs.read (brgb,0,(nwidth+npad)*3*nheight);
     int nindex=0;
     for(int j=0;j<nheight;j++){
     for(int i=0;i<nwidth;i++){
     ndata [nwidth*(nheight-j-1)+i]=
     (255&0xff)<<24
     | (((int)brgb[nindex+2]&0xff)<<16)
     | (((int)brgb[nindex+1]&0xff)<<8)
     | (int)brgb[nindex]&0xff;
     nindex+=3;
     nindex+=npad;
     Toolkit kit=Toolkit.getDefaultToolkit();
     image=kit.createImage(new MemoryImageSource(nwidth,nheight,
     ndata,0,nwidth));
     else
          JOptionPane.showMessageDialog(null, "The choosen BMP image is not 24bit" +
                    "only 24bit bitmap is supported for BMP image.",
               "Invalid image", 0);
          image=(Image)null;
     fs.close();
     }catch (Exception e){
     System.out.println(e);
     return image;
//     --- Private constants
     private final static int BITMAPFILEHEADER_SIZE = 14;
     private final static int BITMAPINFOHEADER_SIZE = 40;
     //--- Private variable declaration
     //--- Bitmap file header
     private byte bitmapFileHeader [] = new byte [14];
     private byte bfType [] = {'B', 'M'};
     private int bfSize = 0;
     private int bfReserved1 = 0;
     private int bfReserved2 = 0;
     private int bfOffBits = BITMAPFILEHEADER_SIZE + BITMAPINFOHEADER_SIZE;
     //--- Bitmap info header
     private byte bitmapInfoHeader [] = new byte [40];
     private int biSize = BITMAPINFOHEADER_SIZE;
     private int biWidth = 0;
     private int biHeight = 0;
     private int biPlanes = 1;
     private int biBitCount = 24;
     private int biCompression = 0;
     private int biSizeImage = 0x030000;
     private int biXPelsPerMeter = 0x0;
     private int biYPelsPerMeter = 0x0;
     private int biClrUsed = 0;
     private int biClrImportant = 0;
     //--- Bitmap raw data
     private int bitmap [];
     //--- File section
     private FileOutputStream fo;
     //--- Default constructor
     public void saveBitmap (String parFilename, Image parImage, int
     parWidth, int parHeight) {
     try {
     fo = new FileOutputStream (parFilename);
     save (parImage, parWidth, parHeight);
     fo.close ();
     catch (Exception saveEx) {
     saveEx.printStackTrace ();
     * The saveMethod is the main method of the process. This method
     * will call the convertImage method to convert the memory image to
     * a byte array; method writeBitmapFileHeader creates and writes
     * the bitmap file header; writeBitmapInfoHeader creates the
     * information header; and writeBitmap writes the image.
     private void save (Image parImage, int parWidth, int parHeight) {
     try {
     convertImage (parImage, parWidth, parHeight);
     writeBitmapFileHeader ();
     writeBitmapInfoHeader ();
     writeBitmap ();
     System.out.println("finished");
     catch (Exception saveEx) {
     saveEx.printStackTrace ();
     * convertImage converts the memory image to the bitmap format (BRG).
     * It also computes some information for the bitmap info header.
     private boolean convertImage (Image parImage, int parWidth, int parHeight) {
     int pad;
     bitmap = new int [parWidth * parHeight];
     PixelGrabber pg = new PixelGrabber (parImage, 0, 0, parWidth, parHeight,
     bitmap, 0, parWidth);
     try {
     pg.grabPixels ();
     catch (InterruptedException e) {
     e.printStackTrace ();
     return (false);
     pad = (4 - ((parWidth * 3) % 4)) * parHeight;
     biSizeImage = ((parWidth * parHeight) * 3) + pad;
     bfSize = biSizeImage + BITMAPFILEHEADER_SIZE +
     BITMAPINFOHEADER_SIZE;
     biWidth = parWidth;
     biHeight = parHeight;
     return (true);
     * writeBitmap converts the image returned from the pixel grabber to
     * the format required. Remember: scan lines are inverted in
     * a bitmap file!
     * Each scan line must be padded to an even 4-byte boundary.
     private void writeBitmap () {
     int size;
     int value;
     int j;
     int i;
     int rowCount;
     int rowIndex;
     int lastRowIndex;
     int pad;
     int padCount;
     byte rgb [] = new byte [3];
     size = (biWidth * biHeight) - 1;
     pad = 4 - ((biWidth * 3) % 4);
     if (pad == 4) // <==== Bug correction
     pad = 0; // <==== Bug correction
     rowCount = 1;
     padCount = 0;
     rowIndex = size - biWidth;
     lastRowIndex = rowIndex;
     try {
     for (j = 0; j < size; j++) {
     value = bitmap [rowIndex];
     rgb [0] = (byte) (value & 0xFF);
     rgb [1] = (byte) ((value >> 8) & 0xFF);
     rgb [2] = (byte) ((value >> 16) & 0xFF);
     fo.write (rgb);
     if (rowCount == biWidth) {
     padCount += pad;
     for (i = 1; i <= pad; i++) {
     fo.write (0x00);
     rowCount = 1;
     rowIndex = lastRowIndex - biWidth;
     lastRowIndex = rowIndex;
     else
     rowCount++;
     rowIndex++;
     //--- Update the size of the file
     bfSize += padCount - pad;
     biSizeImage += padCount - pad;
     catch (Exception wb) {
     wb.printStackTrace ();
     * writeBitmapFileHeader writes the bitmap file header to the file.
     private void writeBitmapFileHeader () {
     try {
     fo.write (bfType);
     fo.write (intToDWord (bfSize));
     fo.write (intToWord (bfReserved1));
     fo.write (intToWord (bfReserved2));
     fo.write (intToDWord (bfOffBits));
     catch (Exception wbfh) {
     wbfh.printStackTrace ();
     * writeBitmapInfoHeader writes the bitmap information header
     * to the file.
     private void writeBitmapInfoHeader () {
     try {
     fo.write (intToDWord (biSize));
     fo.write (intToDWord (biWidth));
     fo.write (intToDWord (biHeight));
     fo.write (intToWord (biPlanes));
     fo.write (intToWord (biBitCount));
     fo.write (intToDWord (biCompression));
     fo.write (intToDWord (biSizeImage));
     fo.write (intToDWord (biXPelsPerMeter));
     fo.write (intToDWord (biYPelsPerMeter));
     fo.write (intToDWord (biClrUsed));
     fo.write (intToDWord (biClrImportant));
     catch (Exception wbih) {
     wbih.printStackTrace ();
     * intToWord converts an int to a word, where the return
     * value is stored in a 2-byte array.
     private byte [] intToWord (int parValue) {
     byte retValue [] = new byte [2];
     retValue [0] = (byte) (parValue & 0x00FF);
     retValue [1] = (byte) ((parValue >> 8) & 0x00FF);
     return (retValue);
     * intToDWord converts an int to a double word, where the return
     * value is stored in a 4-byte array.
     private byte [] intToDWord (int parValue) {
     byte retValue [] = new byte [4];
     retValue [0] = (byte) (parValue & 0x00FF);
     retValue [1] = (byte) ((parValue >> 8) & 0x000000FF);
     retValue [2] = (byte) ((parValue >> 16) & 0x000000FF);
     retValue [3] = (byte) ((parValue >> 24) & 0x000000FF);
     return (retValue);
}

You dont have to write a whole program to read and write BMP files, rather I would recommend you to use latest version of JAVA.
Java version 5 supports reading and writing of BMP images :)
File file = new File("walkleft.bmp");
BufferedImage bi = ImageIO.read(file);   // Here u can read bmp images
ImageIO.write(BufferedImage, "bmp", new File("newimage.bmp"); //Same way you can write themCheers

Similar Messages

  • HT1473 I recently had to restore my laptop back to factory settings and lost my itunes music. I have imported all my cds again but i have some music on my ipad mini and am having problems importing this back into my itunes file. please help as this is dri

    I have recently reset my laptop to factory settings and whilst doing so have lost my music files. I have uploaded my cds but am having trouble moving music from my ipad mini back to music file or itunes.

    iTunes sync is one way from iTunes library to an iOS device.
    You will need third party software such as TouchCopy to transfer from iOS to your computer.

  • TS3899 How do I fix my email account on my iphone 5? I have been having problems with my hotmail on my phone. Please help.

    At first I deleted my account as suggested by the support article and instaled my hotmail account again.
    Now I don't have access to my email anymore.
    Please help.

    No, hotmail is having problems:
    http://bostinno.streetwise.co/2013/08/15/hotmail-outage-hotmail-is-down-for-user s-still-photos/
    http://www.engadget.com/2013/08/14/outlook-outage/
    http://www.infoworld.com/d/applications/microsofts-skydrive-outlookcom-are-down- some-users-224940
    http://mashable.com/2013/08/14/outlook-down/
    http://techcrunch.com/2013/08/14/microsoft-acknowledges-outlook-com-messenger-sk ydrive-outages/

  • I am having problems updating my iPhoto on my MacBook Air, please help?

    I started to update iPhoto on my MacBook Air, but I had bad wifi at home so I paused it. But now that I have good and fast wifi, I press Resume and it asks for my apple ID, so I put it, but then it says that the connection failed, can someone please help!

    Back up all data.
    Quit the App Store application if it's running. Launch the Terminal application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad. Click Utilities, then Terminal in the icon grid.
    Triple-click anywhere in the line below to select it, then drag or copy it — do not type — into the Terminal window:
    open $TMPDIR../C
    Press return. A folder should open. From that folder, delete the subfolder named "com.apple.appstore".
    Launch the App Store and try again.

  • Having problems saving PDF version properties in PDF files

    We have to set the Acobat version to Adobe Acrobat 5.0 (PDF 1.4) in our PDF files.
    The PDF Version properties change even after they are set using any of the following 3 methods:
    1.      Document > Reduce File Size and then  Save As 
              (In my past experience  - if you only “save” the file, it doesn’t save some of the settings)
    2.      Also set them using -  Advanced   > PDF Optimizer and then  Save As.
    3.      These properties were originally set in the Adobe PDF Settings in the Word file before the PDF was created:
    Compatibility : Adobe Acrobat 5.0 (PDF 1.4)
    When I close the file and re-open, the version is not what I set – it doesn’t save.
    Is there something that has to be set in Adobe to save the PDF Version property??
    I'm using Adobe Acrobat Pro v9.
    Thanks -- Karen

    If you use Save or Save as (except the new AAx move of Reduce File Size and PDF Optimize to the save as menu) you will get a current version based on your Acrobat. To get a prior version you have to either create it with compatibility set in the print driver or PDF Maker or you have to used Reduce File Size or PDF Optimize to get a prior version. Maybe that is why they moved those two items to the save as menu so folks would realize that option.
    If you save the file (other than with one of the 2 options mentioned) the version will revert to your current version. It sounds like you may be doing that in some way and losing the type. You can check by opening the PDF in a text editor (like WORD) and looking at the first characters of the file -- should read PDF 1.4. If it does, then you were successful. Of course, do not save the file from the text editor.
    Since you are using AA9, DO NOT use Save As. Use either the Reduce File Size under the Document menu or the PDF Optimize under the Advanced>Print Production menu as I recall. Then close Acrobat, but do not save again. If you do, you will be right back to an AA9 document.

  • I am having problems exporting Firefox bookmarks to Google Chrome. Please help. (Firefox is using too much of the memory.)

    problems importing bookmarks from Firefox to Chrome.
    Help.

    Bookmarks > Show All Bookmarks -> Import & Backup - Export HTML...
    Then import that file into Chrome.

  • Having trouble with reading hex from an input file - please help

    Hi, I have a txt file with rows of hex, and I need to read each line and add it to an int array. So far I have:
    BufferedReader fileIn = new BufferedReader(new FileReader("memory.txt"));
                    int count = 0 ;
                    String temp = fileIn.readLine();
                    int file_in = Integer.parseInt(temp) ;
                    while(temp!=null) {
                         data[count] = file_in;
                         temp = fileIn.readLine();
                         file_in = Integer.parseInt(temp,16);// Integer.parseInt() ;
                         count++ ; /* increment counter */
                    } memory.txt:
    4004000
    4008000
    3FDF4018
    4108200
    3C104001
    FFFFFFE8
    4010C6C0
    FFFFFFE8
    94000000The above code crashes on the third input (my guess is becuase there are letters in and it can't parseInt letters.
    I think I need to parse it into an array of chars instead, however I don't know how to get from the string (temp) to the char array.
    can anyone help?

    ok turns out it's just a null pointer exception on the data[count] line, becuase I've only initialised the first two slots of data. i didn't see it before becase it was just throwing an error and i never printed it out.
    here's how I've defined data:
    in the class
    int[] data;just before the code to input the file data:
    for ( int i = 0; i < length; i++ )       
                    data [ i ] = 0;thinking this shoudl go through all the array and initialise it. but it gives a NullPointerException on the data=0; line.
    any ideas?
    Edited by: rudeboymcc on Feb 6, 2008 10:50 PM
    Edited by: rudeboymcc on Feb 6, 2008 10:51 PM

  • Having problem saving longer name in system 10.4.11?

    having problem saving longer name in system 10.4.11 and try to copy file from server its changes name into shorter form

    Hello, is it just 'Showing a shorter name, or actually shortening it?
    How long are these names?

  • I am having problems saving certain images

    I am having problems saving certain images. For example, on Ebay while viewing an auction item, when you click on the image to view the larger picture it opens in a new window. With Internet Explorer, you can "right-click" and "save picture as". With Firefox 3.6.9 the "save picture as" option is not availabale. Other options such as save "save page as" are available, but not "save as," or "save picture as." Any ideas? Thanks

    I have found a solution to the problem. Apparently there is an addon to fix this. Had no idea a specific google search for "trouble saving images on ebay" would turn up anything.
    https://addons.mozilla.org/en-US/firefox/addon/13802/

  • I am having problems importing some CDs into iTunes on a laptop with Windows 8. Most CDs import without problem. The ones I can't import can be imported into iTunes with Windows 7. Does anybody know why this problem is occurring?

    I am having problems importing some CDs into iTunes on a laptop with Windows 8. Most CDs import without problem. The ones I can't import can be imported into iTunes with Windows 7. Does anybody know why this problem is occurring?

    First-off, this seems to be a general problem with 10.4 (across all the operating systems of which I am aware).  Unfortunately, I cannot provide a permanent solution but, if you need a quick fix, this will (hopefully) work for you.
    For some inexplicable reason, iTunes no longer recognises standard Windows paths.  For example:
    Y:\Music\Buddy Holly\Buddy Holly - Rave On.mp3
    The end result is that it will import a playlist with no content. 
    It will, however, recognise the equivalent Apple paths which look like this:
    file://localhost/Y:/Buddy Holly/Buddy Holly - Rave On.mp3
    It is possible to convert your existing playlists using a few basic replace commands in something like Notepad.  In my case, I made some code changes in my music manager and now generate two sets of playslists (one standard and one to accommodate iTunes).
    Forgive me foir stating the obvious but please remember to make sure that the disk / path containing your music is accessible when doing the import otherwise you will probably get a blank result.  Note that you can do a bulk import by selecting all the (revised) playlists and dragging them onto the iTunes sidebar.
    I am sorry that this is not a "clean" solution but it will work if you are in a bind.  The only alternative of which I am aware is to wait for Apple to fix the problem.

  • Having problems saving contacts on 4s after reset caused by disabling

    Am having problems saving contacts manually on my iPhone 4S after total restore caused by disabling. Can anyone help.

    In case of ur memory card there are different options available to you to get rid of the corrupt/unwanted data in your card.
    menu--installations--application manager--remove the unwanted application....... in ur case themes
    menu--tools--memory---options---format memory card......
    remember everything including ur factory installed apps will be deleted......... but u can always download them later either from nokia or google them...
    or insert ur card in any reader or laptop and check for virus and also the hidden folders....... if there is something left of the application then u will find it in the hidden folders and delete it.......
    Articles posted courtesy engadget
    keep us updated about the progress.... if u like wat I have to offer then click on khudos.

  • I am having problems loading sampler patches into the exs24 sampler, when i got into edit menu and load multiple samples all the samples r greyed out and i cannot slect them, any help with this would be much appreciated

    I am having problems loading sampler patches into the exs24 sampler, when i got into edit menu and load multiple samples all the samples r greyed out and i cannot slect them, any help with this would be much appreciated

    It is very difficult to offer troubleshooting suggestions when the "os version" you are using is unknown as each os has their own troubleshooting solutions. 
    How large is your hard drive and how much hard drive space do you have left? 

  • I'm getting this problem when trying to update my iphone 3gs it says that the iphone software could not be contacted and I went on youtube got some advise to go into my hard drive to fix the error I have nothing in my host file please help me if you can

    I'm getting this problem when trying to update my iphone 3gs it says that the iphone software could not be contacted and I went on youtube got some advise to go into my hard drive to fix the error I have nothing in my host file please help me if you can this is all new to me.

    Read this: iOS 4: Updating your device to iOS 5 or later
    ... oh I think it is a 3gs or a 3
    This makes a difference. What does it say in Settings > General > About?

  • HT201413 Help! Having problem to restore my iPhone 4. Who can help?  Error (-1)

    Help! Having problem to restore my iPhone 4. Can anyone help? I have an erro message, (-1)

    Error 1 or -1
    This may indicate a hardware issue with your device.
    Follow Troubleshooting security software issues, and restore your device on a different known-good computer.
    If the errors persist on another computer, the device may need service.

  • How to converting a flash clip into a bmp file quickly

    Hi,
    I’d like to get help on converting a flash clip into a
    bmp file. I have an application developed with ActiveX technology.
    There is a flash control embedded in the ActiveX control, which has
    a printing button. The end users can press the printing button to
    print the flash picture as well as other text content.
    I get the flash picture for printing in follow steps:
    1.Create a BitmapData object
    var bmp:BitmapData = new BitmapData(w, h, false);
    2.Obtain the image of current flash
    bmp.draw(mc, mc.transform.matrix, new ColorTransform(), 1,
    new Rectangle(x, y, w, h));
    3.Get pixels of flash image one by one in loop, and save them
    into a PixelCollection
    bmp.getPixel(col, row);
    4.Move the PixelCollection into flash container
    fscommand("print", load_PixelCollection);
    5.Ocx control gets the PixelCollection and converts it into
    BMP format
    But I find it is very slow when action script gets pixels one
    by one. Getting pixels of a middle size flash may spend one minute.
    It is hard for our customer to stand. Does anyone have idea to get
    the flash image quickly? 
    Any help is appreciated.
    Shi Hang

    What about the built-in print methods, wouldn't it be better
    to use those here?
    Getting all pixel values is a time intensive process, because
    of the amount of pixels. It may be a bit faster if you split the
    getPixel() loop over some frames, but I'm not exactly sure how to
    do that (just read it somewhere).
    If the content is fixed, you could create the pixel array in
    the background while the user looks at it. This is quite some
    overhead, but when the user decides to print, the array would
    already be there.
    Finally, not helpful here, but interesting:
    quote:
    BitmapData.getPixels()
    No longer do you have to loop through every pixel in a
    bitmap, one at a time with getPixel to send a bitmap to the server.
    This method returns a ByteArray containing the hexadecimal color
    value of each of the pixels in the specified rectangular region of
    a bitmap. Use this method in conjunction with the new ZLib
    compression method; ByteArray.compress() to compress and send a
    bitmap over the wire to a server so it can be converted into a file
    ready for downloading.
    (from
    http://www.flashguru.co.uk/actionscript-3-new-capabilities/)
    This will be available in AS 3.
    hth,
    blemmo

Maybe you are looking for

  • Saving a Adobe Pdf so the toolbars are not viewable and as a jpg without blurry images.

    Hi I have recently purchased a copy of Adobe Acrobat Pro 11 for the first time. I used to create all my documents in Word and then save as a PDF. When hen opening the PDF it would just show the PDF document without toolbars etc. Now when I open it I

  • Need Help with ACTIONSCRIPT for Interactive Music Video

    I am trying to create an interactive music video in After Effects and Flash. The concept is that while the music video is taking place the user can  decorate the hair of the woman with any of the objects they select.   There will be predetermined ani

  • Removing data and passwords

    I have MacBookPro from 2008.  I am running Lion 10.7.5 on the system.  There is a startup disk application in my utilities.  I also have a VMWare partition with Window (dont scream).  I want to barter this system with someone so I need to remove all

  • White screen with apple logo and rotating cog

    Is this a sign that my 27inch imac is overheating. Do I have enough ventilation around it? how much space should I have around the outside of my mac?

  • How do you install firefox 4 for testing purposes?

    I am trying to find as many versions of firefox for web testing but I would be happy with 3.6 4 and 5. I've got 3.6 and 5 but cannot find a working installer for 4. Can i get a link to it?