how can i send image via activities in android - java

I have an application that allow users to choose picture from native gallery then I show this image in image view widget.
My question is:
1-i have to send this image to another Activity. How can i do it.
2-in the receiver Activity i should show it in image view widget as in image not link or Something
I tried this code but it gives me a RunTime Error
Bitmap image = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.RGB_565);
 view.draw(new Canvas(image));
 String url = Images.Media.insertImage(getContentResolver(), image,"title", null);

Just follow the below steps...
Uri uri = null;
1) on any click event use the below code to open native gallery
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"),0);
This will open gallery select picture will return you to your activity. OnActivity result.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
try {
uri = Uri.parse(data.getDataString());
imageView.setImageUri(uri);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
break;
}
}
2) Also instead of passing the image you can pass the URI to next activity as you pass string and inthe secont activity you get it using intent.
Intent i = new Intent(this, Second.class);
i.putExtra("URI", uri.toString() );
startActivity(i);
and in the second activity
String uri = getIntent().getStringExtra("URI");
Now you have string just set it to the image view like below
imageView.setImageUri(Uri.parse(uri));

Use intent putExtra and send uri of the image user selected in Acvtivity1 and in second activity use intent getExtra to read the uri
Refer this answer https://stackoverflow.com/a/7325248/308251

Maybe this is not what you're looking for and it's a bit poor but saved my life when I needed to pass objects between Activities.
public class MagatzemImg {
private static MagatzemImg instance = null;
private static Bitmap img;
public MagatzemImg(){
img=null;
}
public static MagatzemImg getInstance() {
if (instance == null)
instance = new MagatzemImg();
return instance;
}
public static void setImg(Bitmap im){
img = im;
}
public static Bitmap getImg(){
Bitmap imgAux = img;
img = null;
return imgAux;
}
}
And then from the new activity:
MagatzemImg.getInstance();
image = MagatzemImg.getImg();
You can 'assure' to the new Activity that the image exists inside the Static Class through putExtra("image",true) or something else you prefer, like checking if the "image" is null.

Related

Show an image in opengl is working with pictures from gallery but from camera doesn't

I have some troubles to display images in OpenGL.
Actually I'm able to display images from gallery in opengl. The problem occurs when I try to show one from the camera.
For me, OpenGL have to display the image from the camera as it does with the gallery ones. Obviously I'm making something wrong.
Any help will be appreciated.
Intent from gallery:
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/");
startActivityForResult(intent, 2);
Intent from camera:
Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePic.resolveActivity(getPackageManager()) != null) {
File imagen = controler.createPhotoFile(getExternalFilesDir(Environment.DIRECTORY_PICTURES));
if (imagen != null) {
photoUri = FileProvider.getUriForFile(this, "my.fileprovider", imagen);
takePic.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(takePic, 1);
}
}
This is my onActivityResult where I send the URI to a method which convert it to a bitmap and send it.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case 1:
sendImagenPanel(photoUri);
break;
case 2:
sendImagenPanel(data.getData());
break;
}
}
}
private void sendImagenPanel(Uri uri) {
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
final Bitmap imagen = controler.getCroppedBitmap(controler.scaledBitmap(bitmap, 256));
final CasillaOG casilla = ((GLSurfacePanel) gLViewPanel).getRendererPanel().getCuboSelected();
gLViewPanel.queueEvent(new Runnable() {
#Override
public void run() {
casilla.loadNewTexture(imagen);
casilla.setImagen(imagen);
}
});
gLViewPanel.requestRender();
}
In case someone is interested. I realize that the problem is not on the method that calls OpenGL. If I run the same code on the onActivityResult works from the gallery requestCode but not on the camera one, in my Samsung Galaxy Tab A. Why I mention my device? because if I run the app on a Huawei P9 lite, the gallery images are not display either. In both cases appears the next problem on the console:
call to opengl es api with no current context (logged once per thread)
After search that problem, I suppose that the intents of the camera and gallery use OpenGL and its originate a conflict with my own OpenGL environment.
Finally, I opted to set a bitmap field and add the texture in on the onDrawFrame. Obviously, with a boolean to make it one time.

Currently running fragment closes and gets back into previous activity when try to import photo from gallery

Currently running fragment closes and gets back into previous activity when trying to import photo from gallery and set it to ImageView.
I want to set the imported image to an ImageView which is in the fragment. But when I select the image it closes the current fragment and goes back to the previous activity.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
if(requestCode == 1000){
try {
Uri returnUri = data.getData();
Bitmap bitmapImage = null;
bitmapImage = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), returnUri);
ImageView iv = getView().findViewById(R.id.profile_image);
iv.setImageBitmap(bitmapImage);
getFragmentManager().popBackStackImmediate();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I want choose an image from the gallery and set it to an ImageView which is in the currently running fragment without getting closing it.
I tried putting getFragmentManager().popBackStackImmediate(); in OnActivityResult() in my fragment. But it doesn't work.

Wait the result of an activity

I have a class(A) who need to take a picture, so I create an other class(B) with this responsibility. But the problem is, that A don't wait the result of B. How can I do that?
Here is my code :
Class which take the picture
static final int REQUEST_IMAGE_CAPTURE = 1;
Bitmap image = null;
public void takePicture(Context context, Activity activity) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
activity.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
image = (Bitmap) extras.get("data");
}
}
public Bitmap getImage(){
return image;
}
The method which call the the Camera class
public void openCamera() {
Bitmap image = null;
camera.takePicture((Context) _addView, (Activity) _addView);
image = camera.getImage();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
byte[] picture = outStream.toByteArray();
_addView.SetCameraPicture(picture);
}
While taking pictures what you are doing is opening another app(startActivityForResult) which is capable of taking pictures. When the app finishes taking the picture you are sent the data through an intent which you listen using onActivityResult. The other class B must be an
Activity(startActivityForResult() can be called only from an Activity).
So with your scenario, you must first open Activity B, then take the picture,
put the result into an intent and start Activity A with that data, which just does not make any sense. If you want to follow DRY principles put your photo taking method into a utility class and dependency inject your class to wherever you need it. Hope this helps.
You can always try to make class B async and then let class A await the method of class B

Picture taken from camera getting blur

I have integrated crop image library in my application which have function for take and use picture taken via camera. My developer have done it as expected but now when I have checked via take picture from camera than after take picture and set it on crop page, its getting blur before we set it.My developer is out of coverage for some task. I have asked library developer and they have given me solution for integrate code like below
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);Uri outputFileUri = Uri.fromFile(new File(context.getExternalCacheDir().getPath(), "pickImageResult.jpeg"));intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
and My developer have integrated code like below in my application
#Override
public void onClick(DialogInterface dialog, int which) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent,REQ_PHOTO_CAMERA);
}
}
as well method like below
public final int REQ_PHOTO_CAMERA=243;
public final int REQ_PHOTO_GALLERY=346;
public final int REQ_APP_GALLERY=427;
public final int ACTION_CHANGE_BACKGROUND=1;
public final int ACTION_CHANGE_AUTHOR=2;
private int mChangeAction;
public void onActivityResult(int req,int res,Intent data){
if(res==RESULT_OK){
if(req==REQ_PHOTO_CAMERA){
Bitmap cameraImg = (Bitmap) data.getExtras().get("data");
cropAndSaveImage(cameraImg);
//updateCustomImage(cameraImg);
}else if(req==REQ_PHOTO_GALLERY){
try {
Bitmap imgGallery = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
// updateCustomImage(imgGallery);
cropAndSaveImage(imgGallery);
} catch (IOException e) {
// e.printStackTrace();
}
}else if (req == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
Uri resultUri = result.getUri();
Log.e("ImageUrl",resultUri.getPath());
updateCustomImage(BitmapFactory.decodeFile(resultUri.getPath()));
}else if(req==REQ_APP_GALLERY){
String imgPath=data.getStringExtra("ImagePath");
try {
InputStream inputStream=getAssets().open(imgPath);
Bitmap image=BitmapFactory.decodeStream(inputStream);
cropAndSaveImage(image);
} catch (IOException e) {
}
}
}
}
public void cropAndSaveImage(Bitmap imgPicked){
ImageLoader.getInstance().saveTempImage(imgPicked);
CropImage.activity(ImageLoader.getInstance().getTempImageUri())
.setInitialCropWindowPaddingRatio(0)
.setFixAspectRatio(false)
.setAspectRatio(1,2)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
let me know what I am missing ?
Note : we have used this library : Link
Thanks
Your original image taken using camera will be here-
Uri outputFileUri = Uri.fromFile(new File(context.getExternalCacheDir().getPath(), "pickImageResult.jpeg"));
in this file.
the Bitmap cameraImg = (Bitmap) data.getExtras().get("data"); is just a thumbnail returned.

Android Launching Camera Intent from Fragment

I currently have an activity that hosts multiple fragments and I am on my third fragment of a collection.
In that fragment I use an Intent to launch either the Camera or Gallery. See code:
public Intent getImageIntent() {
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = context.getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
intent.setPackage(packageName);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
cameraIntents.toArray(new Parcelable[] {}));
// Calling activity should exeecute:
// startActivityForResult(chooserIntent, 1);
return chooserIntent;
}
After that the onActivityResult executes:
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mProductBitmap = (Bitmap) extras.get("data");
imgProduct.setImageBitmap(mProductBitmap);
}
Where mProductBitmap is a Bitmap Global Variable and imgProduct is an ImageView already initialized.
For some reason, first: The Camera option force closes the app, and gets a null pointer from the actual fragment itself, like the fragment items are all null again.
Second: The gallery options (More then one) don't error out but don't show the image either.
Any help would be appreciated. I've looked at every response possible, but not many people call an intent from a fragment that isn't the initial fragment that the activity is hosting.
Thanks!
EDIT:
Found out sometimes my Context is Null after the onActivityResult. If anyone has encountered this help is appreciated. Thanks.
EDIT: Below is by onActivityResult method, most of the time the first if should be executed.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK) {
handleSmallCameraPhoto(intent);
} else {
if (requestCode == 1) {
InputStream stream = null;
if (intent == null) {
System.out.println("DATA IS NULL..");
} else {
try {
if (mProductBitmap != null) {
mProductBitmap.recycle();
}
stream = getActivity().getContentResolver().openInputStream(
intent.getData());
mProductBitmap = BitmapFactory.decodeStream(stream);
System.out.println(mProductBitmap);
System.out.println("Setting image result");
imgProduct.setImageBitmap(mProductBitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (stream != null)
try {
stream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
}
}
}
Your photo is saved in PATH_TO_SAVE location.
You should in onActivityResult do something like this:
File file = new File(PATH_TO_SAVE);
Bitmap bmp = BitmapFactory.decodeFile(file.getPath());

Categories