On Android, the Bitmap object is transferred between two activities.

Source: Internet
Author: User

On Android, the Bitmap object is transferred between two activities.

On Android, the Bitmap object is transferred between two activities.

Because I am not doing Android applications for a long time, when I first pass Bitmap objects between android systems, I directly use Intent. the putExtra method was implemented. At that time, I chose an Image ROI region, so it worked very well, however, when I tried to upload the entire image as a Bitmap object to another Activity, I always got an error fatal bind error. I was very depressed for a long time, later, google discovered that the method of passing Bitmap objects in this way is incorrect. There is a size limit for transferring Bitmap between activities, and the size limit is very small. The image of 512x512 will certainly get my above error, so I thought of the method of saving it to the SD card first and then passing the path, but the SD card belongs to external storage and may not be particularly convenient, later, I saw someone passing Bitmap objects between two activities and other Java objects supporting serialization through internal storage. So I wrote this blog. The key points are as follows:

1. Download the image from the HTTP client and display it through the ImageView object.

2. Pass the Bitmap object on ImageView from the current Activity to another

Activity and displayed

3. Passing Java object data based on serialization

 

First, let's take a look at how I implemented the HTTP client to download images, use the asynchronous Task interface to implement the HTTP client to download images, and update the ImageView through Handler. The Code is as follows:

 

package com.example.sharedemo;import java.io.IOException;import java.io.InputStream;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.AsyncTask;import android.os.Handler;import android.os.Message;import android.util.Log;public class ImageLoadTask extends AsyncTask
 
   {private Handler handler;public ImageLoadTask(Handler handler) {this.handler = handler;}protected void onPostExecute(Bitmap bitmap) {Message msg = new Message();msg.obj = bitmap;handler.sendMessage(msg);}@Overrideprotected Bitmap doInBackground(String... urls) {Bitmap bitmap = null;// create HTTP clientHttpClient httpclient = new DefaultHttpClient();try {// GET requestLog.i("image-url", urls[0]);HttpGet httpRequest = new HttpGet(urls[0]);HttpResponse httpResponse = httpclient.execute(httpRequest);if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// get entity from responseHttpEntity httpEntity = httpResponse.getEntity();// read streamInputStream is = httpEntity.getContent();bitmap = BitmapFactory.decodeStream(is);is.close();Log.i("image", "already get the image by url : " + urls[0]);}} catch (ClientProtocolException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {httpclient.getConnectionManager().shutdown();}return bitmap;}}
 

 

In the current Activity, the View is switched to the corresponding Activity through the event response on the button, and Java serialized data transmission is also implemented. The MainActivity code is as follows:

 

Package com. example. using demo; import java. io. byteArrayOutputStream; import java. io. fileOutputStream; import android. app. activity; import android. content. context; import android. content. intent; import android. graphics. bitmap; import android. graphics. matrix; import android. graphics. drawable. bitmapDrawable; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; im Port android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. imageView; public class MainActivity extends Activity implements OnClickListener {public final static String pai_bitmap_command = "share-image"; public final static String pai_text_data_command = "share-text-data"; private Handler handler; @ Overrideprotected void onCreate (Bundle savedI NstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); setupOnClickListener ();} private void setupOnClickListener () {Button bitmapBtn = (Button) this. findViewById (R. id. bitmapShareBtn); bitmapBtn. setTag (pai_bitmap_command); bitmapBtn. setOnClickListener (this); Button textDataBtn = (Button) this. findViewById (R. id. mapShareBtn); textDataBtn. setTag (pai_text_data_command); t ExtDataBtn. setOnClickListener (this); final ImageView imageView = (ImageView) this. findViewById (R. id. imageView1); handler = new Handler () {public void handleMessage (Message msg) {Bitmap bitmap = (Bitmap) msg. obj; if (bitmap! = Null) {/* // to prevent memory overflow caused by the large size of the original image, first reduce the source Image Display and then release the memory occupied by the original Bitmap. Bitmap smallBitmap = zoomBitmap (bitmap, bitmap. getWidth ()/5, bitmap. getHeight ()/5); // release the resource bitmap. recycle (); // display the image imageView. setImageBitmap (smallBitmap); imageView. invalidate (); */imageView. setImageBitmap (bitmap) ;}}; ImageLoadTask task = new imageloadtask(handler1_task.exe cute ("http://img.blog.csdn.net/20150607143208238");} public static Bitmap zoomBitmap (Bitmap bitmap, int width, int height) {int w = bitmap. getWidth (); int h = bitmap. getHeight (); Matrix matrix = new Matrix (); float scaleWidth = (float) width/w); float scaleHeight = (float) height/h); matrix. postScale (scaleWidth, scaleHeight); // do not change the original image size Bitmap newbmp = Bitmap. createBitmap (bitmap, 0, 0, w, h, matrix, true); return newbmp;} @ Overridepublic void onClick (View v) {Object tag = v. getTag (); Log. I ("command", tag. toString (); if (pai_bitmap_command.equals (tag) {Intent intent = new Intent (this. getApplicationContext (), ImageProcessActivity. class); ImageView imageView = (ImageView) this. findViewById (R. id. imageView1); Bitmap bitmap = (BitmapDrawable) imageView. getDrawable ()). getBitmap (); intent. putExtra ("selectedImage", bitmap); intent. putExtra ("name", "lena"); intent. putExtra ("description", "Super beauty"); this. startActivity (intent);} else if (pai_text_data_command.equals (tag) {Intent intent = new Intent (this. getApplicationContext (), ImageProcessActivity. class); ImageView imageView = (ImageView) this. findViewById (R. id. imageView1); Bitmap bitmap = (BitmapDrawable) imageView. getDrawable ()). getBitmap (); // save it first then pass URIImageInfoBean dto = new ImageInfoBean (); String uri = createImageFromBitmap (bitmap); dto. setDescription ("Super beauty"); dto. setName ("lena"); dto. setUri (uri); intent. putExtra ("tiger", dto); this. startActivity (intent) ;}} public String createImageFromBitmap (Bitmap bitmap) {String fileName = "myImage"; try {ByteArrayOutputStream bytes = new ByteArrayOutputStream (); bitmap. compress (Bitmap. compressFormat. JPEG, 100, bytes); FileOutputStream fo = openFileOutput (fileName, Context. MODE_PRIVATE); fo. write (bytes. toByteArray (); fo. close ();} catch (Exception e) {e. printStackTrace (); fileName = null;} Log. I ("fileName", fileName); return fileName ;}}

 

The code for reading and assembling Bitmap objects in another Activity is as follows:

 

Package com. example. using demo; import java. io. fileNotFoundException; import android. app. activity; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. OS. bundle; import android. widget. imageView; import android. widget. textView; public class ImageProcessActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); s EtContentView (R. layout. share_info); backFillData ();} private void backFillData () {Object obj = this. getIntent (). getExtras (). get ("tiger"); ImageView imageView = (ImageView) this. findViewById (R. id. imageView1); TextView text1 = (TextView) this. findViewById (R. id. textView1); TextView text2 = (TextView) this. findViewById (R. id. textView2); try {if (obj! = Null & obj instanceof ImageInfoBean) {ImageInfoBean dto = (ImageInfoBean) obj; Bitmap bitmap = BitmapFactory. decodeStream (this. openFileInput (dto. getUri (); imageView. setImageBitmap (bitmap); imageView. invalidate (); // refreshtext1.setText ("name:" + dto. getName (); text2.setText ("Description:" + dto. getDescription (); return ;}} catch (FileNotFoundException e) {e. printStackTrace ();} Bitmap bitmap = (Bitmap) this. g EtIntent (). getParcelableExtra ("selectedImage"); String name = this. getIntent (). getExtras (). getString ("name"); String description = this. getIntent (). getExtras (). getString ("description"); if (bitmap! = Null) {imageView. setImageBitmap (bitmap); imageView. invalidate (); // refresh} if (name! = Null) {text1.setText ("name:" + name) ;}if (description! = Null) {text2.setText ("description:" + description );}}}
The corresponding Java serialized object class code is as follows:

 

 

package com.example.sharedemo;import java.io.Serializable;public class ImageInfoBean implements Serializable {/** *  */private static final long serialVersionUID = 1L;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getUri() {return uri;}public void setUri(String uri) {this.uri = uri;}private String name;private String description;private String uri;}
Final Statement:

 

Do not forget to add the network access permission to the Manifest file.

 

 

The first button, "Pass image", will demonstrate the error, and the second button, "Pass text data]

 

The correct processing result is displayed as follows:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.