Android studios - How to pass image from gallery to another activity - android

I rarely ask on stackoverflow, but I asked a questions recently and got a great answer! so I'll try again!
I've been working on a very simple photofilter app that adds the effect through code.
What I've been struggling with is to send a picture from whenever I open up gallery to choose a picture to another activity. I mean, I would like to choose a image from gallery, then send it to a preview activity.
Whenever I take a photo from the camera, it works and I get the photo with the added filter, but my problem is that whenever I choose an image from gallery, my app crashes. I tried to use URI instead but it didn't turn out well so I rather convert the picture I take to a bitmap and thereafter send it to the activity. Could anyone help me with this please?
Thank you!
MainAcitivty
package com.example.alek.leszealots;
import java.io.File;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.content.Intent;
import android.net.Uri;
public class MainActivity extends AppCompatActivity {
//Deklarasjoner for fremtidlig var
Button galleryButton;
Button cameraButton;
public static final int PICK_IMAGE = 1;
private static final int CAMERA_REQUEST = 1;
Bitmap thumbnail;
int CAPTURE_REQUEST;
Uri thumbFile;
File mTempFile;
int REQUEST_CODE_CHOOSE_PICTURE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Gjør klar menu knappene
galleryButton = (Button) findViewById(R.id.button);
cameraButton = (Button) findViewById(R.id.button2);
//Gallery knapp
galleryButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View view) {
/*Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
getIntent.setType("image/*");
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});
startActivityForResult(chooserIntent, PICK_IMAGE);*/
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, false);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Complete Action Using"), PICK_IMAGE);
}
});
//Camera knapp
cameraButton.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAPTURE_REQUEST);
}
});
}
//Sender lagret bilde i bitmap til sendImage som deretter sender videre til NextActivity i extra
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == CAPTURE_REQUEST) {
thumbnail = (Bitmap) data.getExtras().get("data");
sendImage();
}
else if (requestCode == PICK_IMAGE) {
thumbnail = (Bitmap) data.getExtras().get("data");
sendImage();
}
}
}
private void sendImage() {
Intent intent = new Intent(MainActivity.this, NextActivity.class);
intent.putExtra("image", thumbnail);
startActivity(intent);
}
}
NextActivity
package test.test;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class NextActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
ImageView imageView = (ImageView) findViewById(R.id.imageView);
//Ser ut som denne kan ta imot fra Gallery option også.
Bundle extras = getIntent().getExtras();
if (extras != null) {
Bitmap image = (Bitmap) extras.get("image");
if (image != null) {
imageView.setImageBitmap(changeBitmapContrastBrightness(image, 20, -255));
}
}
}
public static Bitmap changeBitmapContrastBrightness(Bitmap bmp, float contrast, float brightness)
{
ColorMatrix cm = new ColorMatrix(new float[]
{
contrast, 0, 0, 0, brightness,
0, contrast, 0, 0, brightness,
0, 0, contrast, 0, brightness,
0, 0, 0, 1, 0
});
Bitmap ret = Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), bmp.getConfig());
Canvas canvas = new Canvas(ret);
Paint paint = new Paint();
paint.setColorFilter(new ColorMatrixColorFilter(cm));
canvas.drawBitmap(bmp, 0, 0, paint);
return ret;
}
}
activity_next
<ImageView
android:id="#+id/imageView"
android:layout_width="330dp"
android:layout_height="369dp"
app:srcCompat="#mipmap/ic_launcher"
tools:layout_editor_absoluteX="38dp"
tools:layout_editor_absoluteY="37dp" />
</android.support.constraint.ConstraintLayout>
activity_main
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="105dp"
tools:layout_editor_absoluteY="189dp" />
</android.support.constraint.ConstraintLayout>
Edit:
https://pastebin.com/Ukc2Ui4g

Related

send image as a bit map (By Intent or Sharedpreference)

I want to pass image in one activity to another activity.I tried many time.but my app gonna crash.plz edit my code with necessary changes.
Sender activity:
camera=(ImageButton)findViewById(R.id.camera);
gallery=(ImageButton)findViewById(R.id.gallery);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i =new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
startActivityForResult(i, 50);
}
});
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 40);
}
});
}
Receiver activity:
package com.androidlink.navigation_bottom;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class Image_set_Activity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_set_);
ImageView IV = (ImageView) findViewById(R.id.simpleImageView);
}
}
in onActivityResult
Bitmap photo = (Bitmap) data.getExtras().get("data");
Log.d("===uploadPhoto","camera : "+photo);
*//* Passing BITMAP to the Second Activity *//*
Intent intentCamera = new Intent(this, SecondAvtivity.class);
IntentCamera.putExtra("BitmapImage", photo);
startActivity(intentCamera);
in seconActivity
Bitmap fromCamera = getIntent().getParcelableExtra("BitmapImage");
imageView.setImageBitmap(fromCamera)
Try to Use This Code
Frist Classs
ImageView img=findViewById(R.id.imgId);
BitmapDrawable bmd= (BitmapDrawable) img.getDrawable();
Bitmap bt= bmd.getBitmap();
final byte[] imgarry = bt.getNinePatchChunk();
Intent intent = new Intent (FirstClass.this,SecondClass.class);
Intent.putExtra(“imgs”,imgarry);
startActivity(intent);
Second Class
Intent in = getIntent();
byte[] ary= in.getByteArrayExtra(“imgs”);
Bitmap bm= BitmapFactory.decodeByteArray(ary,0,ary.length);
imageView.setImageBitmap(bm);

How to send image one activity to another activity?

I am new in android.i want to pass image in one activity to another activity.I tried many time.but my app gonna crash.plz edit my code with necessary changes.
Sender activity:
camera=(ImageButton)findViewById(R.id.camera);
gallery=(ImageButton)findViewById(R.id.gallery);
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i =new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
startActivityForResult(i, 50);
}
});
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 40);
}
});
}
Receiver activity:
package com.androidlink.navigation_bottom;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class Image_set_Activity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_set_);
ImageView IV = (ImageView) findViewById(R.id.simpleImageView);
}
}
Try to override onActivityResult(). For further reading - https://developer.android.com/training/basics/intents/result
Try this code For sending the image
ImageView imageview = (ImageView) findViewById(R.id.Tab);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
final byte[] arr = bitmap.getNinePatchChunk();
imageView.setOnClickListener(View v)
{
Intent intent = new Intent (MainActivity.this,bbb.class);
Intent.putExtra(“image”,arr);
startActivity(intent);
}
For getting the image
Intent I = getIntent();
byte[] arr1 = i.getByteArrayExtra(“image”);
Bitmap map = BitmapFactory.decodeByteArray(arr,0,arr.length);
imageView.setImageBitmap(map);

Passing Picture from activity to another activity

I have three Activity objects.
I want to transfer picture from FirstActivity To SecondActivity by passing in AlarmREceiver
This is my code of FirstActivity
package com.testcamera.hassanechafai.testcamera;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.util.Calendar;
import java.util.Date;
public class FirstActivity extends ActionBarActivity {
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
ImageView imgView;
private String imgPath;
Intent myIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
imgView = (ImageView) findViewById(R.id.ImageView);
Button butCamera = (Button) findViewById(R.id.Button1);
butCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
final Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
setImageUri());
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
Button butGallery = (Button) findViewById(R.id.Button2);
butGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, ""),
PICK_IMAGE);
}
});
final EditText save = (EditText) findViewById(R.id.EditText1);
Button myBtn = (Button) findViewById(R.id.Save);
myBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int time = Integer.parseInt(save.getText().toString());
if (time > 0) {
myIntent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, time);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(getApplicationContext(), "Starting Activity in: " + time + " seconds", Toast.LENGTH_SHORT).show();
finish();
}
}
});
}
public Uri setImageUri() {
// Store image in dcim
File file = new File(Environment.getExternalStorageDirectory()
+ "/DCIM/", "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
imgView.setImageBitmap(decodeFile(selectedImagePath));
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
imgView.setImageBitmap(decodeFile(selectedImagePath));
Intent intent = new Intent(this, CallActivity.class);
intent.putExtra("BitmapImage", selectedImagePath);
} else {
super.onActivityResult(requestCode, resultCode,
data);
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaColumns.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
}
This code of AlarmReceiver
package com.testcamera.hassanechafai.testcamera;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm time reached", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClassName("com.testcamera.hassanechafai.testcamera", "com.testcamera.hassanechafai.testcamera.CallActivity");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
This code of SecondAcitivy (I call it CallActivity)
package com.testcamera.hassanechafai.testcamera;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
public class CallActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
ImageView image = (ImageView)findViewById(R.id.ImageView);
}
I need to transfer photo from FirstActivity To SecondAcitivy by passing in AlarmActivity can someone help me ?
in your myBtn onClick you forgot to add myIntent.putExtra("theKeyUsed","yourConvertedStringUri");
then in your Receiver class you are missing that too.
IN your CallAcitvity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_call);
String path = getIntent().getStringExtra("theKeyUsed"); // in your case "BitmapImage"
ImageView image = (ImageView)findViewById(R.id.ImageView);
// now set image using the path
}
In general pass your uri.toString() as a string extra with your intent to the preferred activity and retrieve..
feel free to delete the question if you find your solution

Android ImageView content disapearing after showing

My application does this: takes a photo, then show the photo in an ImageView. The weird thing is that the photo is displayed for about a second (after taking it with the camera), and then the ImageView is empty again.
This is my code:
publish.xml
<ImageView
android:id="#+id/itemImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
PublishActivity.java
package ar.com.guiagratis;
import java.io.File;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class PublishActivity extends Activity {
final int TAKE_PICTURE_REQUEST_CODE = 115;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.publish);
}
public void btnNextClick(View v) {
// TODO: disable all buttons
//Intent intent=new Intent(getApplicationContext(), TakePhotoActivity.class);
// startActivityForResult(intent, TAKE_PICTURE_RESULT_CODE);
Toast.makeText(getApplicationContext(), "Sacate una foto viteh", Toast.LENGTH_SHORT).show();
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photoFile = new File(Environment.getExternalStorageDirectory(), "Photo.png");
Uri imageUri = Uri.fromFile(photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, TAKE_PICTURE_REQUEST_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case TAKE_PICTURE_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK) {
File photoFile = new File(Environment.getExternalStorageDirectory(), "Photo.png");
Uri imageUri = Uri.fromFile(photoFile);
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
imageUri, Toast.LENGTH_LONG).show();
Bitmap myBitmap = BitmapFactory.decodeFile(imageUri.getPath());
BitmapDrawable ob = new BitmapDrawable(myBitmap);
ImageView myImage = (ImageView) findViewById(R.id.itemImage);
myImage.setBackgroundDrawable(ob);
Toast.makeText(getApplicationContext(), "Qué linda foto! ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Hubo un problema al subir la imágen... ", Toast.LENGTH_SHORT).show();
}
}
}
}
Any help will be appreciated.
You're using setBackgroundDrawable(Drawable drawable) which sets the View's background.
If you want to change the ImageView's content you need to use
setImageDrawable(Drawable drawable)
or
setImageBitmap(Bitmap bm)
Ok, I finally found the problem. I was not aware that I need to use onSaveInstanceState and onRestoreInstanceState to store the values I don't want to loose from an Activity when I'm doing certain things, like initiating the Camera and taking a photo.
So I added this code:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("photoUploaded", photoUploaded);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
photoUploaded = savedInstanceState.getBoolean("photoUploaded");
if (photoUploaded) {
File photoFile = new File(Environment.getExternalStorageDirectory(), "Photo.png");
Uri imageUri = Uri.fromFile(photoFile);
Bitmap myBitmap = BitmapFactory.decodeFile(imageUri.getPath());
BitmapDrawable ob = new BitmapDrawable(myBitmap);
ImageView myImage = (ImageView) findViewById(R.id.uploadedImage);
myImage.setBackgroundDrawable(ob);
}
}
and now is working.
Not sure how to do to make this question as solved.

merging image in android

I want to merge two different images of two different size and create a single image out of it and save it in sdcard.The image format what i am using is jpg.Is it possible to create merged image as jpg??
What do you mean by "merge"? You can load your two images as Bitmap objects, create a new Bitmap and an accompanying Canvas, draw your two images into the new Bitmap and then save it as a jpg using:
bitmap.compress(
CompressFormat.JPEG,
95, // or whatever compression ratio you want
new FileOutputStream("/some/location/image.jpg")
);
package com.example.imagemerging;
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.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button btnLoadImage1, btnLoadImage2;
TextView textSource1, textSource2;
Button btnProcessing;
ImageView imageResult;
final int RQS_IMAGE1 = 1;
final int RQS_IMAGE2 = 2;
Uri source1, source2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnLoadImage1 = (Button)findViewById(R.id.loadimage1);
btnLoadImage2 = (Button)findViewById(R.id.loadimage2);
textSource1 = (TextView)findViewById(R.id.sourceuri1);
textSource2 = (TextView)findViewById(R.id.sourceuri2);
btnProcessing = (Button)findViewById(R.id.processing);
imageResult = (ImageView)findViewById(R.id.result);
btnLoadImage1.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);
}});
btnLoadImage2.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_IMAGE2);
}});
btnProcessing.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
if(source1 != null && source2 != null){
Bitmap processedBitmap = ProcessingBitmap();
if(processedBitmap != null){
imageResult.setImageBitmap(processedBitmap);
Toast.makeText(getApplicationContext(),
"Done",
Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),
"Upload The Image",
Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(),
"Select both image!",
Toast.LENGTH_LONG).show();
}
}});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
switch (requestCode){
case RQS_IMAGE1:
source1 = data.getData();
textSource1.setText(source1.toString());
break;
case RQS_IMAGE2:
source2 = data.getData();
textSource2.setText(source2.toString());
break;
}
}
}
private Bitmap ProcessingBitmap(){
Bitmap bm1 = null;
Bitmap bm2 = null;
Bitmap newBitmap = null;
try {
bm1 = BitmapFactory.decodeStream(
getContentResolver().openInputStream(source1));
bm2 = BitmapFactory.decodeStream(
getContentResolver().openInputStream(source2));
int w;
if(bm1.getWidth() >= bm2.getWidth()){
w = bm1.getWidth();
}else{
w = bm2.getWidth();
}
int h;
if(bm1.getHeight() >= bm2.getHeight()){
h = bm1.getHeight();
}else{
h = bm2.getHeight();
}
Config config = bm1.getConfig();
if(config == null){
config = Bitmap.Config.ARGB_8888;
}
newBitmap = Bitmap.createBitmap(w, h, config);
Canvas newCanvas = new Canvas(newBitmap);
newCanvas.drawBitmap(bm1, 0, 0, null);
Paint paint = new Paint();
paint.setAlpha(128);
newCanvas.drawBitmap(bm2, 0, 0, paint);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newBitmap;
}
}
//Layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.example.imagemerging.MainActivity" >
<Button
android:id="#+id/loadimage1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/buttontext_loadimage1" />
<TextView
android:id="#+id/sourceuri1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/loadimage2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/buttontext_loadimage2" />
<TextView
android:id="#+id/sourceuri2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/processing"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/buttontext_processing" />
<ImageView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

Categories

Resources