Tuesday, September 3, 2013

Convert Bitmap to Drawable with BitmapDrawable

To convert Bitmap to Drawable with BitmapDrawable with the code:

     //Convert bitmap to drawable
     Drawable drawable = new BitmapDrawable(getResources(), tempBitmap);

Modify from previouse exercise "Create mirror bitmap with matrix" to load jpg from SDCARD, as Bitmap. Then convert to Drawable with BitmapDrawable.

Convert Bitmap to Drawable with BitmapDrawable


package com.example.androiddrawbitmap;

import java.io.FileNotFoundException;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 Button btnLoadImage;
 TextView textSource;
 ImageView imageResult;
 
 final int RQS_IMAGE1 = 1;

 Uri source;
 Bitmap bitmapMaster;
 Canvas canvasMaster;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  btnLoadImage = (Button)findViewById(R.id.loadimage);
  textSource = (TextView)findViewById(R.id.sourceuri);
  imageResult = (ImageView)findViewById(R.id.result);
  
  btnLoadImage.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    Intent intent = new Intent(Intent.ACTION_PICK,
      android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, RQS_IMAGE1);
   }});
  
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  
  Bitmap tempBitmap;
  
  if(resultCode == RESULT_OK){
   switch (requestCode){
   case RQS_IMAGE1:
    source = data.getData();
    
    
    try {
     tempBitmap = BitmapFactory.decodeStream(
       getContentResolver().openInputStream(source));
     
     //Convert bitmap to drawable
     Drawable drawable = new BitmapDrawable(getResources(), tempBitmap);
     
     imageResult.setImageDrawable(drawable);
     
     textSource.setText(drawable.getClass().toString());
     
    } catch (FileNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    
    break;
   }
  }
 }

}

Layout refer to the exercise "Create mirror bitmap with matrix".

download filesDownload the files.



more: Something about processing images in Android

No comments: