Get a PNG of bitmap byte array

Hey people. Look at the code below (continues after the code). (I use JDE 4.7 and tests on the simulator of Bold 9700 (OS 5.0)).


    private static Bitmap LoadBitmap(String uri) {

        InputStream in = null;
        FileConnection filecon = null;
        String exceptionText = null;
        byte[] bitmapBytes = new byte[1000000];
        boolean fileExists = false;
        int numBytes = 0;

        try {
            filecon = (FileConnection) Connector.open(uri, Connector.READ);    

            if (filecon.exists()) {
                in = filecon.openInputStream();
                numBytes = in.read(bitmapBytes, 0, 1000000);
                in.close();
                if (numBytes != 1)
                    fileExists = true;
            }
        }
        catch (Exception e) {
                    String logMessage = e.getMessage();
                    if ( EventLogger.logEvent( 0x4c9d3452d87922f2L, logMessage.getBytes(), EventLogger.ALWAYS_LOG ) ) {
                        System.out.println("Log Successful!");
                    }
        }

        Bitmap bm = null;

        if (fileExists) {

            String imageExtension = uri.substring(uri.length() - 4); // e.g. .png or .jpg or .gif

            if (imageExtension.equals(".png")) {
                PNGEncodedImage image = (PNGEncodedImage)EncodedImage.createEncodedImage(bitmapBytes, 0, bitmapBytes.length);
                bm = image.getBitmap();   // Chokes at present
            }
            else if (imageExtension.equals(".gif")) {
                GIFEncodedImage image = (GIFEncodedImage)EncodedImage.createEncodedImage(bitmapBytes, 0, bitmapBytes.length);
                bm = image.getBitmap();   // Chokes at present
            }
            else {
                EncodedImage image = EncodedImage.createEncodedImage(bitmapBytes, 0, bitmapBytes.length);
                bm = image.getBitmap();
            }

        }

        return bm;

    }

Your code for reading from a file into a byte array has some problems. More important is the use of an InputStreamReader, which is to convert each byte in a character using the ISO-8859-1 default encoding. You are truncating each character for a byte and those writing in the file, which has probably garbage inside.

Try this for the reading of the resource in a byte array:

InputStream is = convertResourceToFile.getResourceAsStream("/" + resName);
byte[] bytes = IOUtilities.streamToBytes(is);
is.close();

By reading the data back from the file, use a similar code. You should be aware that when you try to read a link like this:

numBytes = in.read(bitmapBytes, 0, 1000000);

There is no guarantee that the entrance is worn out from here that one call. It has guaranteed only that read() will consume at least one character, unless there is no more input. (I have no idea, however, why numBytes is greater than the size of the file. Have you verified that this is indeed the case - that the file is not that big?)

Tags: BlackBerry Developers

Similar Questions

  • BYTE array to float?

    I am relatively new to Labview and haven't found an example of this on these forums.  Any help would be greatly appreciated!

    I read in a stream of characters from a series device, and I would like to convert a 4-byte string (or Byte array) to a float value.  Is there a way to do this in labview?

    For example, I have the table {0x4b, 0x1c, 0 x 90, 0x42} = 0x4b1c9042 = 72.055260 float value

    I can do this in c by:

    Char [] floatarray is {0x4b, 0x1c, 0 x 90, 0x42, 0x00};.

    memcpy (floatarray, & floatvalue sends);

    printf ("float \nMy value is %f", floatvalue);  give 72.055260 for floatvalue

    Is there a way to do this in Labview?

    Note that if you get the chain in that order, you need to invert the first string:

  • Generate PrivateKey using byte array

    Hello

    I'm working on my school project, where I should simulate the DDA authentication. I placed my public and private keys inside byte [] variables in the applet, and in order to encrypt and decrypt messages I need to convert these arrays of bytes to the PublicKey and PrivateKey objects. I know that javacard.security defines a key factory class keyBuilder, but I can't understand how to use this class, to rebuild my keys, which are in the byte array. Is there a way to do this?

    Thank you
    Vuk

    hem. toString? a string? JavaCard know only 8 and 16-bit atomic types and tables. No int. No tank. No java.lang.String.

    How long have you studied javacard?

    the offcard entity will get the keys in arrays of bytes, put them in APDU, send the APDU to the javacard inside the map applet using javax.smartcardio. the javacard applet will then store the buffers received in key forums.

    I think you're mixing offcard code of java and applet javacard "at a distance". There is no magical conduit between java objects and plastic in a card; you need to send APDU commands to the cmdlet to store your keys inside the applet. This means developing a bunch of javacard code that will run in the map, using GlobalPlatform to download the code of the card.

    See here for pointers to base on the map technology.
    APDU and contactless

    Best regards and good luck.

  • Save obj as a byte array?

    is it possible to write a byte array object (in the Air)? Or should I serialize?

    I tried - but get an error...


    function saveObj (obj:Object, sFilename:String) {}

    application path und unterpfad en treat - sonst security error!
    var adir:String = .nativePath (File.applicationDirectory.resolvePath(""))
    var file:File = new queue (adir + "/" + sFilename);

    var fs:FileStream = new FileStream();

    FS. Open (file, FileMode.WRITE);
    fs.writeUTFBytes (dat);
    fs.writeBytes ((obj));
    FS. Close();
    }

    You should get an error... fs.writeBytes takes a ByteStream, not an object. You can create a ByteStream first and then use the method writeObject of it to serialize your object - then what to write in your stream. Something like:

    var ba: ByteArray = new ByteArray();

    ba.writeObject (obj);

    fs.writeBytes (ba);

  • Sending the image byte array

    Hello friends

    Please guide me how can I send a table yte my UIcopmonent bitmap with the size of the 0.4 scale.

    In fact my my UIComponet size is 234 X 390 and I hv to send the byte array to the PHP end with size 90 X 150.

    This is so, how can I draw an image with the smallest size.please guide me almost 0.4 scale image.

    When I usedthis code

    var bmd:BitmapData = new BitmapData(cnvParent.width,cnvParent.height,true,0xffffff);
    var mt:Matrix new matrix());
    Mt.Scale (.4,.4);
    BMD. Draw (cnvParent, MT);
    var jpgencoder:PNGEncoder = new PNGEncoder();
    byteArray = jpgencoder.encode (bmd);

    It shows nothing after conversion to byte array. Please help me out of this problem, I have confused mtotally

    Thanks and greetings

    Vineet osho

    Hello

    If you acknowledged the answers when given to previous requests for help may call a friend people would sound more sincere. You where showed how scaling of images already was what process does not?

    David.

  • How to convert a string to byte array

    Hello

    I want to convert a string with a hexadecimal number in the array of bytes, this string includes a cutting-edge information, but I don't want to add this tip to arry bytes.

    detailed information please see the photo. I hope someone can give me some instructions, thank you very much.

    The accepted solution of Giedrius.S is not correct, based on the image shown in the first post. That the solution will not eliminate the spaces before the tip, and the string to byte array to convert individual characters '0', '8', 'space', '9', etc. for them to byte values. The right solution, based on the image below:

  • Numbers of string to byte array

    I try to use "Byte array to string" if I display the byte array, I can see the last two items are the numbers 4-8 (ASCII 52 56) but when I use the "Byte Array to necklace" and add an indicator of the 48 is missing?  Ignore this palette number 0-9?  Is there another way to easily convert an array of bytes into a string with numbers.  What I am doing wrong?

    I'm looking, but I can't believe I can't find an example of this?


  • Convert Int to byte array.

    Hello

    I am trying to convert an int to an array of bytes and stumbled upon a solution. However, it is not appropriate for BB/J2ME.

    byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
    
    for (byte b : bytes) {
       System.out.format("0x%x ", b);
    }
    

    I have converted into loop, but not an alternative to System.out.format () there is no J2ME.

    How can I convert my whole in byte array?

    Thank you.

    Hi guys, sorry for the delay in responding. Basically, I have to send my ACR122U an int on NFC. If int is more than 255 does not in a single byte then I have to represent in an array of bytes, right?

    I think RexDoug is correct also, I don't understand masking and stuff like that. It's something that I've always been conscious of good :/

    Thank you guys.

    Here's what I went with:

      public byte[] intToBytes(int value) {
    
             return new byte[] {
                        (byte) ((value >>> 24) & 0xff),
                        (byte) ((value >>> 16) & 0xff),
                        (byte) ((value >>> 8) & 0xff),
                        (byte) (value & 0xff),
                      };
        }
    

    REF: http://stackoverflow.com/questions/9587605/java-integer-to-byte-array-blackberry-j2me/9587708#958770...

  • several images capture and read their path to send the byte array to the web service

    Hello

    Have a problem when the image capture, the requirement is to open the camera and capture multiple images, and once done it should send the array of bytes to the web service, wrote the class with reader and Video Control of the code and then using the saved file to store image API, but when the user capture multiple images it replaces previous if I keep the path to say dynamic by using the date and time then how I just know what images are recently captured and their path, one time I know that the path of recently captured using new fileconnection images can read the image byte array.

    Hi Nishant,

    find the attached code. In this demo, you will find:

    (1) the use of the listner log file system

    (2) how to move data from one folder to another.

    (3) how to read file system byteArray.

  • Question about the RAF read byte array, method

    Hello

    I use file access random byte array read method to read a file. I will print each line, when printing to the last line, it is added with some null characters.

    Can you please suggest how to remove null characters in the last line?

    I use file access random byte array read method to read a file. I will print each line, when printing to the last line, it is added with some null characters.

    No, you're ignoring the read count returned by the method and the treatment of the whole buffer.

  • How to convert to unsigned int byte array?

    Greetings,

    I have no particular knowledge of Java programming, and I have a problem with a conversion.

    The exception thrown is "number Format Exception for the input string:"249"when I run the following code:

    ReadBytes = SocketInput.Read (bMessage);
    NetMessage = new String (bMessage);
    NetMessage = NetMessage.substring (0, readbytes);

    If (NetMessage.Equals ("NORES"))
    NetMessage = '0 '.

    int Res = 0;
    Try
    {
    RES = Byte.valueOf (NetMessage);
    }
    catch (NumberFormatException nfe)
    {
    AddMessage ("Number Format Exception" + nfe.getMessage () + "[" + bMessage.toString () + "]");
    }

    The java Byte / byte data type is signed and contains values from-128 to 127. Why not use Integer.valueOf () instead (which is not signed or said by the way) and look
    [url http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html] in Java primitive data types.

    In your code example, there is no byte (byte []) array, while mention you in the subject...

  • How to get the 'index' of an associative array?

    Hello

    Is it possible to get the 'index' of an associative array?

    I saw say about 3000 ID.

    Corresponding to each of these identifiers, thre is a 'key' (the 'key' can repeat for different ID)... tell key1, key2, key3.

    Now, I want to show the top of page 8 keys ().

    Could you please tell me how can I do this?

    Concerning

    Don't know what you are exactly looking for.

    To get the index of an array of assotiative you should do something like

    SQL> declare
       type arr is table of number
                      index by varchar2 (5);
    
       var   arr;
       idx   varchar2 (5);
    begin
       --  fill the array
       for id in 1 .. 12
       loop
          var ('key' || to_char (id, 'fm00')) := id;
       end loop;
    
    --  get the keys
       idx := var.first;
       dbms_output.put_line (idx);
    
       while idx is not null
       loop
          idx := var.next (idx);
          dbms_output.put_line (idx);
       end loop;
    end;
    /
    key01
    key02
    key03
    key04
    key05
    key06
    key07
    key08
    key09
    key10
    key11
    key12
    PL/SQL procedure successfully completed.
    
  • Get the height and width of the jpg or png of bitmap without loading the file

    Is there a way to get the height and width of a bitmap, such as jpg or png file, without loading the complete file of the image first.

    Thank you!

    Hi JamesColeman,

    While you can't get the width and height of the jpg or png without access to the file, you can get this information without access to the entire file. A PNG for example (in raw hex) indicates the width and height of the image it contains. The first 21 bytes contain the file-specific information such as name, etc, but just after the IHDR header 4 bytes indicate the width and the other 4 bytes indicate height. If enough for you to read the first 29 bytes of the PNG to be able to get its dimensions, which, while it still requires access to the file is much easier.

    I have the code to read this information here and if you want to learn more about the specifications you can find information on this site.

    Best wishes

    André

  • How to get the byte Array of image cascading?

    Hello

    I need help to get the array of bytes to the image.

    In fact, I have developed image processing application so I need.

    Thank you.

    Please ask a feature against Blackberry 10 (BBTEN) in the Issue Tracker: http://supportforums.blackberry.com/t5/Java-Development/Developer-Issue-Tracker/td-p/271768

    Stuart

  • Encoding of Bitmaps and arrays of bytes

    Hello

    I was hitting my head several times on my desk for a few days, trying to get my program if care, nothing will do. No other options, I decided that I would ask experts.

    I'm doing a program that will ask the user to select an image, and then encode it to a binary string and store it in an XML file. He will then be able to "decode" the wire and rebuild.

    I followed a few online guides, but I can't seem to get anything to work. My understanding is that I need to penetrate the BitmapData Bitmap from its components, to convert to a "byteArray" who is saved, (or possibly coded) then this byteArray of the data collected and transformed into a clip on the stage. However, no matter what I do, I can't seem to properly recreate the bitmap image, once I got the data... It throws always an "end of file".

    In order to get the basics, I cut my code down to the bare minimum - what is just to load the image from the local file system, enter its bitmapdata, clone and place it in a new Bitmap that is added to the stage. However, I get only ever returned an error message "End of file encountered" - which seems to indicate, to me, is not properly populating the byteArray. (He looks certainly way too short when the trace)

    Help, please!

    Here is my code for the base charger-

    import flash.display.Sprite;
    import flash.events.*;
    import flash.net.*;

    //load image
    var loader:Loader = new Loader();
    var url = "C:\\Data\\cutcord.jpg";
    var urlReq:URLRequest = new URLRequest(url);
    configureLoader(loader.contentLoaderInfo);
    loader.load(urlReq);

    function completeHandler(event:Event):void {

         var imageIn:BitmapData = event.target.content.bitmapData;
         var byteArray:ByteArray = imageIn.getPixels(imageIn.rect);
         var newBitmapData:BitmapData = imageIn.clone();
         
         newBitmapData.setPixels(imageIn.rect, byteArray);
         var newBitmap:Bitmap = new Bitmap(newBitmapData,"auto",true);
         
         this.addChild(newBitmap);
    }

    function configureLoader(dispatcher:IEventDispatcher):void {
         dispatcher.addEventListener(Event.COMPLETE, completeHandler);
    }

    Here's a way to do it.

    I broke it upward into 2 parts. Part is in charge of the original image (to create the ByteArray of).

    Second part (loadImageData()) uses the Base64 encoded ByteArray and convert into an image and display it.

    import flash.display.Loader;
    import flash.net.URLRequest;
    import flash.display.Bitmap;
    import com.dynamicflash.util.Base64;
    import flash.display.BitmapData
    import flash.geom.Rectangle;
    
    var loader:Loader;
    var req:URLRequest;
    var orig_mc:MovieClip;
    var copy_mc:MovieClip;
    var imgWidth:int;
    var imgHeight:int;
    var b64Img:String;
    
    function loaderCompleteHandler(evt:Event):void {
     trace("Application ::: loaderCompleteHandler");
     var ldr:Loader = evt.currentTarget.loader as Loader;
     var origImg:Bitmap = (ldr.content as Bitmap);
     imgWidth = origImg.width;
     imgHeight = origImg.height;
     var origBmd:BitmapData = origImg.bitmapData;
    
     var rect:Rectangle = new Rectangle(0,0,origImg.width, origImg.height);
     var ba:ByteArray = origBmd.getPixels(rect);
     trace("    - bytearray length: ", ba.length);
     // Base64 encode - this is what gets stored (in xml or whatever)
     b64Img = Base64.encodeByteArray(ba);
     //trace("b64Img: ", b64Img);
     // now (pretend) to load the data
     loadImageData();
    }
    
    function loadImageData():void {
     trace("Application: loadImageData");
     // use b64Img as if it was loaded from xml
     // decode Base64 string to ByteArray
     var ba:ByteArray = Base64.decodeToByteArray(b64Img);
     trace("    - bytearray length: ", ba.length);
     // create Rectangle, same size as original
     var rect:Rectangle = new Rectangle(0, 0, imgWidth, imgHeight);
     // crate BitmapData and throw bytearry at it
     var bmd:BitmapData = new BitmapData(imgWidth,imgHeight, false, 0x00000000);
     bmd.setPixels(rect, ba);
     // create (smooth) bitmap from data
     var bm:Bitmap = new Bitmap(bmd, "auto", true);
     // display bitmap in movieclip
     copy_mc.addChild(bm);
     copy_mc.x = imgWidth + 10;
    }
    
    loader = new Loader();
    req = new URLRequest("2.jpg");
    loader.load(req);
    loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
    orig_mc = new MovieClip();
    orig_mc.addChild(loader);
    addChild(orig_mc);
    copy_mc = new MovieClip();
    addChild(copy_mc);
    

    Note that to make this work, you need to save original image width and height (in your xml) as well as the data that is encoded in Base64.

    Another way to do the same thing would be to use JPGEncoder or PNGEncoder to encode the original bitmapdata.

    They're both part of the Flex SDK: http://livedocs.adobe.com/flex/3/langref/mx/graphics/codec/package-detail.html

    But it is also available in the AS3CoreLib: http://code.google.com/p/as3corelib/

    http://code.Google.com/p/AS3corelib/downloads/list

    With PNGEncoder/JPGEncoder you take the bitmapdata and convert it to a png or jpg (such as ByteArray) and that Base64 encoding.

    The difference here is that you would get * real * data image than other languages can understand as well. For example, you can view the image using PHP, or whatever. The following must be able to encode the original image (jpg) BitmapData, ByteArray.

    var jpg:JPGEncoder = new JPGEncoder(80);
    var ba:ByteArray = jpg.encode(origBmd);
    

    To display the image you could use a Loader instance and then call loadBytes()

    var loader:Loader = new Loader();
    loader.loadBytes(ba);
    addChild(loader);
    

    So to rebuild the image is much easier as well (no need of the height or the width of the original image).

    Hope this helps

Maybe you are looking for

  • How to remove the recent update

    Someone in my family installed the last Mozilla 25.0.1 on my computer, which has been deleted and my Norton toolbar, which is not compatible with the new Mozilla. How to get back to what I had before?

  • Cannot perform a scan.

    1 HP photosmart prem web c309n-s. 2. Windows 7 64-bit. 3. an analysis cannot be performed because another program or computer using the hp networking, imaging device. 4. no new material added. 5. my wife and I have laptop HP G72-B27CL.  His laptop co

  • I can't find an option to use my built in webcam

    Hi I have a toshiba satellite pro laptop with built in webcam but I can't find any options to access Ive looked all over the laptop, but can not find anything to do with him or just not what I'm looking for tbh lol help wud be good! x [Moved from com

  • When I try to install MapPoint Europe 2011 I get error 0xC004D301.

    I downloaded a trial version of mappoint europe 2011 and that yesterday I lost the power of the computer as loading and now all I get is this error to initialize license 0xC004D301. Contact support. original title: error initializing license 0xC004D3

  • Cannot use Skype, convenience store, saying that his incompatible

    Programs Application Applications Apps game games Legacy Crash crashes Hang Application Compatibility hangs can anyone help please.  I can't use my Skype.  It is now telling me in the box of trouble shoots I have an incompatible application.  How the