Sunday, 15 July 2012

Converting an image from drawable to byte array in Android -


Since I am sending an image to Parse.com, I have to convert it to a byte array. My first method is to select an image from the gallery and change it in the byte array as follows:

  @Override Secure Zero ActiveEngineer (Int Requestcode, Inc Results, Code, Intent Data) {super .onActivityResult (requestCode, ResultsCode, Data); If (requestCode == RESULT_LOAD_IMAGE & amp; amp; amp; result code == RESULT_OK & tap! = Data) {mMediaUri = data.getData (); String [] filePathColumn = {MediaStore.images.Media.DATA}; Cursor cursor = getContentResolver (). Query (mMediaUri, filePathColumn, null, null, null); Cursor.moveToFirst (); Int columnIndex = cursor.getColumnIndex (filePathColumn [0]); PicturePath = cursor.getString (column index); Cursor.close (); // Image View Image = View (see image) Search ViewById (R.id.imgView); PropertyImage.setImageBitmap (BitmapFactory.decodeFile (picturePath)); Bitmap BMP = bitmapfile. Decodefile (pictured); Bytereon output stream stream = new byteOutStream (); BMP. Commerce (bitmap.compress format.png, 100, stream); ByteArray = stream.toByteArray (); }  

The above code works fine and is stored to successfully parse the image. Now, when I select no picture, the app crashes, obviously bcoz, no data is sent and exception exception is raised.

Now, I want to set a default image, which is to parse my Dressable folder, for example - no picture is selected from the gallery, so the Pars operation is disturbed by zero data Are not there.

I had to set the default image to get started:

  propertyImage = (ImageView) findViewById (R.id.imageViewOfage); PropertyImage.setImageResource (R.drawable.blank_image);  

Now, how do I change this default image to a bitrate, so that it can be sent to parse?

Thanks and Regards

Check my working code:

First use your paintable image by using this method in the bitmap . Public static bitmap DrawBlobeMap (Drawing Drawable) {If (Dryable Installation of Bitmaprvwable) {Return ((Bitmap Drawable Drawable)) .getBitmap (); } Final integer width =! Drawable.getBounds () IsEmpty ()? Drawable .getBounds () Width (): drawable.getIntrinsicWidth (); Last intimate height =! Drawable.getBounds () IsEmpty ()? Drawable .getBounds () Height (): drawable.getIntrinsicHeight (); Last bitmap bitmap = bitmap.centbitmap (width & lt; = 0? 1: width, height & lt; = 0? 1: height, bitmap config.rg_8888); Logs. V ("bitmap width - height:", width + ":" + height); Canvas canvas = new canvas (bitmap); Drawable.setBounds (0, 0, canvas.getWidth), canvas.getight ()); Drawable.draw (canvas); Return bitmap; }

After getting your bitmap object, you need to convert it by using the byte array.

  ByteArrayOutputStream stream = new ByteArrayOutputStream (); Bitmap.compress (bitmap.compress format.png, 100, stream); Byte [] Biteire = Stream. To Batere ();  

No comments:

Post a Comment