I have two activity, First with button, which calls void openCamera, and second, where I need to get bitmap.
I have two questions:
1. Which line of code is saving pictures?
2. How I can take a bitmap from OnActivityResult and get it in another activity?
private void openCamera() {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "New Picture");
values.put(MediaStore.Images.Media.DESCRIPTION, "Taking pic from the Camera");
image_uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
SelectedImage.setImageURI(image_uri);
try {
Bitmap ImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), image_uri);
detectImage(ImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
Don't think about passing it through Bundle (docs: https://developer.android.com/guide/topics/resources/runtime-changes.html#RetainingAnObject)
I think, you should save the image in internal storage of your app and then load it in your second activity.
Here are the answers explaining how to do that: Saving and Reading Bitmaps/Images from Internal memory in Android
Pass image uri as string along with activity intent
mIntent.putExtra("image", image_url.toString());
In the receiving activity get the uri and move your code to generate bitmap there.
String image_url = getIntent().getStringExtra("image");
//your code to get bitmap
Related
I have an app where a user is registered and can have a profile image. In the realtime database I have these information saved. Now I want to be able to change the informatiom, particulary profile image. Here is my realtime database:
When the user clicks on his/hers image the camera intent starts:
private void startCamera() {
//start the camera
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,REQUEST_IMAGE_CAPTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == RESULT_OK) {
//picture as image
Bitmap bp = (Bitmap) data.getExtras().get("data");
mProfileRoundedImageView.setImageBitmap(bp);
//here I want to save Image uri and update my firebase with the new uri...
}
}
}
How can I do that?? I have searched alot how to convert captured image to uri and then update imageurl but with no luck. Please help.
BTW I do not want to save the image to the sd, just convert to uri and update firebase...
You can use the below function.
public Uri getImageUri(Context inContext, Bitmap inImage) {
Bitmap OutImage = Bitmap.createScaledBitmap(inImage, 1000, 1000,true);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), OutImage, "Title", null);
return Uri.parse(path);
}
Just call it in the onActivityResult() after you extract bitmap
Feel free to ask if something is unclear
OK, so here is what I want to do in this android activity:
Press the button that says "choose pic"
Use intent or whatever, and go to choose a pic from your local photo library
Once you have chosen the pic, go to this activity
And this time, the image view below would be set (it will be the picture you've chosen)
I have read this q&a and tried the code below, in the activity, but it didnt work out.
android pick images from gallery
*for the last line I couldn't figure out what to write, I just wanted to set the exact picture
public void choosepic (View v){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.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);
foodpic.setpic
}
As your code says image cannot be set from the method where you launch the intent.
Override method with name onActivityResult() and use the following code in that method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// String picturePath contains the path of selected Image
ImageView imageView = (ImageView) findViewById(R.id.imgView);
Bitmap bmp = null;
try {
bmp = getBitmapFromUri(selectedImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageView.setImageBitmap(bmp);
}
Hope this helps.
I want to be able to send a picture from one user to another in a messaging app like on whatsApp, but I am not sure how to do that. I am using android and parse as my DB. I tried googling and nothing seems to help, I am new on Android development. I would prefer to use it as I do with my texts , since when sending messages between users I am using parse as my database. Can someone please assist, I am able to select the image from galery and load it in an image view but I am not sure how to send it as I would with text. The code that should be under when the button "send" is clicked.
Below is the code that I have. Please have a look at it. I have been trying everything that I can think of but I am not getting anywhere.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
//Everything Okay
if (requestCode == LOAD_IMAGE_RESULTS) {
Uri pickedImage = data.getData();
InputStream inputStream;
try {
inputStream = getContentResolver().openInputStream(pickedImage);
Bitmap selectImage = BitmapFactory.decodeStream(inputStream);
sendPicture.setImageBitmap(selectImage);
selectImage = ((BitmapDrawable) sendPicture.getDrawable()).getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectImage.compress(Bitmap.CompressFormat.PNG, 5, stream);
byte[] imageRec = stream.toByteArray();
final ParseObject imgMsgToBeSent = new ParseObject("SentImages");
final ParseFile fileRenamed;
//create parse file
fileRenamed = new ParseFile("SentImage.png", imageRec);
imgMsgToBeSent.put("receipientId", MessagingActivity.recipientId.toString());
imgMsgToBeSent.put("senderId", MessagingActivity.currentUserId.toString());
imgMsgToBeSent.put("imageReceived", fileRenamed);
sendImgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == R.id.sendImageBtn) {
messageService.sendMessage(MessagingActivity.recipientId.toString(), fileRenamed.toString());
finish();
}
}
});
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Unable to load image",
Toast.LENGTH_LONG).show();
}
}
}
}
For Sharing Image after selected from Gallery ##
First get the image path and than send it via intent like this:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri Imageuri = Uri.fromFile(new File(image));
shareIntent.setType("image/");
shareIntent.putExtra(Intent.EXTRA_STREAM, Imageuri);
startActivity(Intent.createChooser(shareIntent, "ShareWia"));
for sharing image and text both just add one more settype and use put extra with text like this:
Intent shareIntent = new Intent(Intent.ACTION_SEND);
Uri Imageuri = Uri.fromFile(new File(image));
shareIntent.setType("image/");
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, text);
shareIntent.putExtra(Intent.EXTRA_STREAM, Imageuri);
startActivity(Intent.createChooser(shareIntent, "ShareWia"));
Sinch does not support attachments in IM
In my costum camera app I need to transfer a bitmap and a Uri from one activity to another. For some reason I'm getting the FAILED BINDER TRANSACTION error on most phones(I get the error on newer phones but don't on Nexus4 and Galaxy3). I get the same error even when I only try to transfer the Bitmap through an intent(I also tried transfering only the Uri and got the error). From what I've read online the error comes from a memory problem but I don't know how to fix it. I would appreciate any kind of help.
My first Activity:
...
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
tv.setVisibility(View.INVISIBLE);
btn.setVisibility(View.INVISIBLE);
selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
ok.setVisibility(View.VISIBLE);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==btn.getId())
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
if(v.getId()==ok.getId())
{
String stringUri;
stringUri = selectedImageUri.toString();
Intent intent = new Intent(Intent.ACTION_VIEW);
intent .setClass(MainActivity.this, SecondMain.class);
intent .putExtra("KEY", stringUri);
startActivity(intent );
}
}
}
Second Activity:
public static Camera isCameraAvailiable(){
Camera object = null;
try {
object = Camera.open();// attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return object; // returns null if camera is unavailable
}
private Camera.PictureCallback capturedIt = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
if(bitmap==null){
Toast.makeText(getApplicationContext(), "not taken", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "taken", Toast.LENGTH_SHORT).show();
}
cameraObject.release();
}
};
...
String stringUri = null;
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("KEY")) {
stringUri= extras.getString("KEY");
}
selectedImageUri = Uri.parse(extras.getString("KEY"));
float alpha=(float)1/2;
img.setAlpha(alpha);
img.setImageURI(selectedImageUri);
cameraObject = isCameraAvailiable();
showCamera = new ShowCamera(this, cameraObject);
frame.addView(showCamera);
}
public void snapIt(View view){
redo.setVisibility(View.VISIBLE);
ok.setVisibility(View.VISIBLE);
snap.setVisibility(View.INVISIBLE);
cameraObject.takePicture(null, null, capturedIt);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId()==ok.getId())
{
Intent intent = new Intent(SecondMain.this, Blend.class);
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[]byteArray=stream.toByteArray();
intent.putExtra("image", byteArray);
String stringUri;
stringUri = selectedImageUri.toString();
intent .putExtra("KEY", stringUri);
startActivity(intent);
It is not a memory problem, it's a problem with transferring your image with your intent. You see, Bundle has a limit of how much data it can transfer from one end to the other, currently it's only 1MB. You will problems on all modern phones with a decent camera, as the image exceeds 1MB limit, some old phones with low end camera will work. You need to rethink on how you are going to be transfering the image.
You can
Save it to a file first, send the only the path to it (that's how selecting an image from the gallery works)
Save it to SQL and retrive it on the other end
Make a hodler class with a static variable of image (the most simple)
Make a custom class of Application and put it there for the time being.
Downscale and compress the image before it's transferred
So I've got my image to successfully pass to a URI...however I don't know how to save it or convert it to a bitmap while still maintaining resolution. Any suggestions? Thank you.
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// CALL THE PICTURE (this works)
File t = new File (STORAGE_PATH + "savedAndroid.jpg");
mURI = Uri.fromFile(t);
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mURI);
startActivityForResult(i,0); //0 is default camera
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
imageView.setImageURI(mURI); //this seems to work...by itself
//save the image or convert it to a bitmap to use with tesseract...
}
InputStream is = context.getContentResolver().openInputStream(mURI);
Bitmap bitmap = BitmapFactory.decodeStream(is, null, new BitmapFactory.Options());
Then use it however you want.
Hope this helps.