15SrHM8GT8rOkCLHViEKlK-ejrCocgl6A Android: Loading Photo and Show in new Activity - Cooking & Coding

mercoledì 10 ottobre 2012

Android: Loading Photo and Show in new Activity

LOADING PHOTO IN ANOTHER ACTIVITY

This is a very useful code because sometimes you need to load a photo from gallery or other location and showing in another activity. Create a new project on eclipse and insert the code below.

MainActivity.java



package com.lucapinta.loadshow;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity implements OnClickListener {
 
 Button choosePicture;
 Bitmap bmpFile;
 final String JPEG_PICTURE = "JPEG_PICTURE";
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  choosePicture = (Button) this.findViewById(R.id.button1);
  choosePicture.setOnClickListener(this);

} //end on Create

 //** Actiond load photo
 public void onClick(View v) {
  Intent choosePictureIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
  startActivityForResult(choosePictureIntent, 0);
 }

 
//*************** Metodo LoadGALLERY 
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
  super.onActivityResult(requestCode, resultCode, intent);

  if (resultCode == RESULT_OK) {
   Uri imageFileUri = intent.getData();
    bmpFile = loadBitmap(imageFileUri);

     } //end if
 }// end onAcitivity    
  
    
//************* Load Image   
   private Bitmap loadBitmap(Uri imageFileUri) {
    Display currentDisplay = getWindowManager().getDefaultDisplay();

    float dw = currentDisplay.getWidth();
    float dh = currentDisplay.getHeight();

    Bitmap returnBmp = Bitmap.createBitmap((int) dw, (int) dh, Bitmap.Config.ARGB_4444);

    try {
     // Load up the image's dimensions not the image itself
     BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
     bmpFactoryOptions.inJustDecodeBounds = true;
     returnBmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);

     int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / dh);
     int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / dw);

     Log.v("HEIGHTRATIO", "" + heightRatio);
     Log.v("WIDTHRATIO", "" + widthRatio);

     // If both of the ratios are greater than 1, one of the sides of the
     // image is greater than the screen
     if (heightRatio > 1 && widthRatio > 1) {
      if (heightRatio > widthRatio) {
       // Height ratio is larger, scale according to it
       bmpFactoryOptions.inSampleSize = heightRatio;
      } else {
       // Width ratio is larger, scale according to it
       bmpFactoryOptions.inSampleSize = widthRatio;
      }
     }

     // Decode it for real
     bmpFactoryOptions.inJustDecodeBounds = false;
     returnBmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
    
    } catch (FileNotFoundException e) {
     Log.v("ERROR", e.toString());
    }

    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    returnBmp.compress(Bitmap.CompressFormat.PNG, 100, baos); //bmp is the bitmap object   
    byte[] b = baos.toByteArray();
    
    //Lunch image in another activity
   Intent nextActivity = new Intent(getApplicationContext(), ImageShow.class);
    nextActivity.putExtra(JPEG_PICTURE, b);
    startActivity(nextActivity);
    
    return returnBmp;
    
   } //loadImage


 
 
//*********************  Change 
    @Override 
    public void onConfigurationChanged(Configuration newConfig) {
     super.onConfigurationChanged(newConfig);
    } //end onCC

} //end class    

main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
       
<TableLayout android:layout_height="wrap_content" 
    android:layout_width="fill_parent"
 android:paddingTop="2sp" 
 android:paddingBottom="2sp"
 android:padding="3sp"  >
<TableRow>     
    

   <TextView
       android:id="@+id/textView1"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:text="Select Device"
       android:textAppearance="?android:attr/textAppearanceMedium" />

</TableRow>
<TableRow>

     <Button
          android:id="@+id/button1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Select Image" />

</TableRow>
</TableLayout>


</LinearLayout>


CLASS Loading and show photo

ImageShow.java

package com.lucapinta.loadshow;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;

public class ImageShow extends Activity {
 
  private static final String JPEG_PICTURE ="JPEG_PICTURE";
 private Bitmap bitmap; // Img Originale

 byte [] jpegPicture;
   
   Button button1, button2, button3;
   
   ImageView imageView;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // This is the only way camera preview work on all android devices at full screen
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
       
        // No title, no name: Full screen
       getWindow().setFormat(PixelFormat.TRANSLUCENT);
       requestWindowFeature(Window.FEATURE_NO_TITLE);
       getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
       
           // Set the default layout for this activity
        //this.setContentView(R.layout.imageview); // try different set -- FULL SCREN
        
        this.setContentView(R.layout.imageview2); // try different set -> image centred
        
   
    imageView = (ImageView)findViewById(R.id.imageView);
    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
    
        
//********** Get JPEG image from extras from the Intent that launch this activity
         Bundle bundleExtras = getIntent().getExtras();
         if (bundleExtras.containsKey(JPEG_PICTURE)) {
                 jpegPicture = bundleExtras.getByteArray(JPEG_PICTURE);                          
                         int offset = 0;
                         int length = jpegPicture.length;
                         
                // Obtain bitmap from the JPEG data object
                bitmap = BitmapFactory.decodeByteArray(jpegPicture, offset, length);
                imageView.setImageBitmap(bitmap);
           } 
         else {
              // JPEG data is not in the bundle extra received
              finishActivity(RESULT_CANCELED);
      }//end else

         
} //end onCreate --


      //**************  Change Configurations    
            @Override 
            public void onConfigurationChanged(Configuration newConfig) {
                super.onConfigurationChanged(newConfig);
            }//end methods      
      
      
} //end class    



imageview2.xml



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" />

<TableLayout android:layout_height="wrap_content" 
    android:layout_width="fill_parent"
 android:paddingTop="1sp" 
 android:paddingBottom="2sp"
 android:padding="3sp"  />
<

<TableRow/>    
     
       <Button
           android:id="@+id/button1"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Button1" />

       <TextView
           android:id="@+id/textView1"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="U can use thsi space as u want!!" />
              
        <Button
           android:id="@+id/button2"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:text="Button2" />
</TableRow>
<TableRow>


  <ImageView android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/imageView"/>
</TableRow>
</TableLayout>    
</LinearLayout>

Nessun commento:

Posta un commento

Follow me

In

Fli

Created with flickr badge.