I take photo
Photo gets stored in ImageView
I want to be able to send that photo stored in the ImageView to my pc via Bluetooth when user selects Send To Pharmacy button.
Is this possible? Since the image is constantly changing, how would I do this? I have looked up some tutorials and StackOverflow questions but they all seem to be focused on images in a drawable folder already.
But in this case, the image is different every time the user takes a photo. I just want to know how I can send the current photo that is in the ImageView, and send it to a PC via Bluetooth. Thanks for any help I appreciate this.
package com.cognizant.expressprescriptionregistration;
import static android.os.Environment.getExternalStoragePublicDirectory;
public class Register extends AppCompatActivity {
Button bPicButton;
ImageView imageView;
String pathToFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
bPicButton = findViewById(R.id.bTakePhoto);
imageView = findViewById(R.id.imagePrescription);
// Ask for permission for Camera and Storage
if (Build.VERSION.SDK_INT >= 23){
requestPermissions(new String[] {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if camera successfully pops up and takes photo, set photo in ImageView
if (resultCode == RESULT_OK){
if (requestCode == 1){
Bitmap bitmap = BitmapFactory.decodeFile(pathToFile);
imageView.setImageBitmap(bitmap);
}
}
}
// Take Picture button onClick listener
public void takePhoto(View view) {
setPhotoTaken();
}
private void setPhotoTaken() {
Intent takePhoto = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Make sure the app can handle our intent
if (takePhoto.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
// Created Photo file
photoFile = createPhotoFile();
// Get path of our photo file
if (photoFile != null) {
pathToFile = photoFile.getAbsolutePath();
Uri photoUri = FileProvider.getUriForFile(Register.this, "com.cognizant.expressprescriptionregistration.fileprovider", photoFile);
takePhoto.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
startActivityForResult(takePhoto, 1);
}
}
}
// Create the file where the photo will be stored
private File createPhotoFile() {
// Name of file
String name = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
// Location of storage
File storedDir = getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File photo = null;
try {
// Creates file in storedDir
photo = File.createTempFile(name, ".jpg", storedDir);
} catch (IOException e) {
e.printStackTrace();
}
return photo;
}
// Send to Pharmacy Button
public void sendToPharmacy(View view) {
}
}
You can get current image from ImageView by getting the bitmap from ImageView:
Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
After this you can save and share the bitmap.
I am able to send individually Image and text but I want to send image and text together
Please help me anyone
Use multipart. Using multipart you can send images video and other files with your text data. Various library is available to send data in multipart. Ion is one of them
one way is You can convert image to Base64 string in web api
public static String imageToString(Bitmap BitmapData) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BitmapData.compress(Bitmap.CompressFormat.PNG, 100, bos);
byte[] byte_arr = bos.toByteArray();
String file = Base64.encodeToString(byte_arr, Base64.DEFAULT);
//appendLog(file);
return file;
}
you can convert bitmap image to Base64 string in above function and pass string parameter in your api and decode those string in server side
Thanks all of you specially thanks to Bhupat Bheda. I Complete my full project. Now I want to share my research.
private void saveText() {
String image= getStringImage(rotatedBMP);
ImageCapture imageCapture = new ImageCapture();
imageCapture.Name = prescriptionName.getText().toString();
imageCapture.Remarks = remarks.getText().toString();
imageCapture.ImageURL=mCurrentPhotoPath;
imageCapture.PhotoName=photoName;
imageCapture.Image=image;
imageCapture.Id = _ImageId_Id;
if (_ImageId_Id == 0) {
restService.getService().InsertPrescription(imageCapture, new Callback<ImageCapture>() {
#Override
public void success(ImageCapture imageCapture, Response response) {
Toast.makeText(Prescription.this, "New Record Inserted.", Toast.LENGTH_LONG).show();
Intent intent=new Intent(getApplicationContext(),Home.class);
startActivity(intent);
}
#Override
public void failure(RetrofitError error) {
Toast.makeText(Prescription.this, error.getMessage().toString(), Toast.LENGTH_LONG).show();
}
});
}
}
private void takePhoto() {
dispatchTakePictureIntent();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
Log.i(TAG, "onActivityResult: " + this);
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK) {
setPic();
}
}
String mCurrentPhotoPath;
String photoName;
static final int REQUEST_TAKE_PHOTO = 1;
File photoFile = null;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
For Details [How to send Image and text from android application to sql server using web api][1]
https://esoftpanel.blogspot.com/2017/04/how-to-send-image-and-text-from-android.html
I am new to xamarin and I want to take a picture from the camera when I click on a button on my mainactivity and then, once the picture taken, display it in an imageView in an other activity.
Can you help me?
Here's what I have right now :
MainActivity :
costsButton.Click += delegate
{
Intent intent = new Intent(MediaStore.ActionImageCapture);
StartActivityForResult(intent, 0);
};
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
var extra = data.GetByteArrayExtra("data");
Intent intent = new Intent(this, typeof(AddFrais));
intent.PutExtra("picture", extra);
StartActivity(intent);
}
AddFrais.cs :
namespace Projet_stage_2017
{
[Activity(Label = "AddFrais")]
public class AddFrais : Activity
{
ImageView picturefrais;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.AddFrais);
picturefrais = FindViewById<ImageView>(Resource.Id.ImageFrais);
var image = Intent.GetByteArrayExtra("picture") ?? null;
Bitmap bitmap = BitmapFactory.DecodeByteArray(image, 0, image.Length);
picturefrais.SetImageBitmap(bitmap);
}
}
}
I don't know what to put on the "PutExtra" in the mainActivity to be able to create a bitmap on AddFrais.cs...
Thanks for helping !
Try this:
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
// It's a good idea that you check this before accessing the data
if (requestCode == 0 && resultCode == Result.Ok)
{
//get the image bitmap from the intent extras
var image = (Bitmap)data.Extras.Get("data");
// you might also like to check whether image is null or not
// if (image == null) do something
//convert bitmap into byte array
byte[] bitmapData;
using (var stream = new MemoryStream())
{
image.Compress(Bitmap.CompressFormat.Png, 0, stream);
bitmapData = stream.ToArray();
}
Intent intent = new Intent(this, typeof(AddFrais));
intent.PutExtra("picture", bitmapData);
StartActivity(intent);
}
// if you got here something bad happened...
}
Then in your second Activity:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.AddFrais);
picturefrais = FindViewById<ImageView>(Resource.Id.ImageFrais);
//Get image from intent as ByteArray
var image = Intent.GetByteArrayExtra("picture");
if (image != null)
{
//Convert byte array back into bitmap
Bitmap bitmap = BitmapFactory.DecodeByteArray(image, 0, image.Length);
picturefrais.SetImageBitmap(bitmap);
}
}
As you can see your second activity code is most likely the same, I just added a validation to prevent NullReferenceException if the image is not well extracted from the intent.
Hope this helps!
I am trying to remove a ParseFile from a ParseUser. The ParseFile is a profile picture that was created, and I would like to provide my users will the ability to change there profile picture when convenient to them.
I am looking for a way to delete the old ParseFile associated with the profile picture, and just store a new one.
I cannot seem to get the .remove("photo"); method to work properly, and am not sure if I am going about this the wrong way. What would be the best method to do something like this?
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == RESULT_LOAD_IMAGE) {
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap bitmap = extras2.getParcelable("data");
ivProfilePic.setImageBitmap(bitmap);
final ParseUser currentUser = ParseUser.getCurrentUser();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bitmapByte = stream.toByteArray();
final ParseFile profilePicture = new ParseFile(
"profilePicture", bitmapByte);
profilePicture.saveInBackground(new SaveCallback() {
public void done(ParseException e) {
if (e != null) {
} else {
// check to see if ParseFile exists, if it does
// delete it and set new ParseFile
currentUser.remove("photo");
currentUser.put("photo", profilePicture);
currentUser.saveInBackground();
updateViewsWithProfileInfo();
}
}
});
}
}
}
if (resultCode != RESULT_OK) {
return;
}
This line of code stops everything from working properly. If you remove this the ParseFile is removed / updated properly.
I have an app published and one of the fundamental features is to allow the user to take a picture, and then save that photo in a specific folder on their External Storage.
Everything seems to be working fine, but I've gotten two reports now that claim that after taking a photo, and clicking "Done" to exit the camera (and return back to the Activity), the app is Forced Closed, bringing the user back to the home screen.
This happens on a Samsung Nexus S and the Galaxy Tab. Below I've posted my code to show I set up my intent and how I handle saving and displaying the photo in onActivityResult(). Any guidance on what might be causing it to crash after they click "Done" to exit the camera app, would be greatly appreciated!
Again, this seems to be working fine on most devices but I was wondering if their is a more efficient, universal approach I should be taking. Thank you
How I'm firing the Camera Intent
case ACTION_BAR_CAMERA:
// numbered image name
fileName = "image_" + String.valueOf(numImages) + ".jpg";
output = new File(direct + File.separator + fileName); // create
// output
while (output.exists()) { // while the file exists
numImages++; // increment number of images
fileName = "image_" + String.valueOf(numImages) + ".jpg";
output = new File(outputFolder, fileName);
}
camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
uriSavedImage = Uri.fromFile(output); // get Uri of the output
camera.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage); //pass in Uri to camera intent
startActivityForResult(camera, 1);
break;
default:
return super.onHandleActionBarItemClick(item, position);
}
return true;
}
How I'm setting up onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) { // If data was passed successfully
Bundle extras = data.getExtras();
//Bundle extras = data.getBundleExtra(MediaStore.EXTRA_OUTPUT);
/*ad = new AlertDialog.Builder(this).create();
ad.setIcon(android.R.drawable.ic_menu_camera);
ad.setTitle("Save Image");
ad.setMessage("Save This Image To Album?");
ad.setButton("Ok", this);
ad.show();*/
bmp = (Bitmap) extras.get("data"); // Set the bitmap to the bundle
// of data that was just
// received
image.setImageBitmap(bmp); // Set imageview to image that was
// captured
image.setScaleType(ScaleType.FIT_XY);
}
}
First lets make it clear - we have two options to take image data in onActivityResult from Camera:
1. Start Camera by passing the exact location Uri of image where you want to save.
2. Just Start Camera don't pass any Loaction Uri.
1 . IN FIRST CASE :
Start Camera by passing image Uri where you want to save:
String imageFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture.jpg";
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile); // convert path to Uri
Intent it = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
it.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(it, CAMERA_RESULT);
In onActivityResult receive the image as:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (RESULT_OK == resultCode) {
iv = (ImageView) findViewById(R.id.ReturnedImageView);
// Decode it for real
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = false;
//imageFilePath image path which you pass with intent
Bitmap bmp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
// Display it
iv.setImageBitmap(bmp);
}
}
2 . IN SECOND CASE:
Start Camera without passing image Uri, if you want to receive image in Intent(data) :
Intent it = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(it, CAMERA_RESULT);
In onActivityResult recive image as:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (RESULT_OK == resultCode) {
// Get Extra from the intent
Bundle extras = data.getExtras();
// Get the returned image from extra
Bitmap bmp = (Bitmap) extras.get("data");
iv = (ImageView) findViewById(R.id.ReturnedImageView);
iv.setImageBitmap(bmp);
}
}
*****Happy Coding!!!!*****
On the camera button click event you can try this:
final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(getTempFile(this)));
startActivityForResult(intent, TAKE_PHOTO_CODE);
declare TAKE_PHOTO_CODE globally as:
private static final int TAKE_PHOTO_CODE = 1;
Add getTempFile Function in the code which will help to save the image named myImage.png you clicked in the sdcard under the folder named as your app's package name.
private File getTempFile(Context context) {
final File path = new File(Environment.getExternalStorageDirectory(),
context.getPackageName());
if (!path.exists()) {
path.mkdir();
}
return new File(path, "myImage.png");
}
Now on OnActivityResult function add this:
if (requestCode == TAKE_PHOTO_CODE) {
final File file = getTempFile(this);
try {
Uri uri = Uri.fromFile(file);
Bitmap captureBmp = Media.getBitmap(getContentResolver(),
uri);
image.setImageBitmap(captureBmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
in case you get Memory issues than add below code:
#Override
protected void onPause() {
image.setImageURI(null);
super.onPause();
}
I hope this will help you
I suspect 3 posible problems may have created your issue:
Some devices return null when you call extras.get("data"); in onActivityResult method so your problem may be a NullPointerException. To solve this, you need to pass the exact URI location to tell the camera app where you want it to store and use it in onActivityResult to retrieve the image as a Bitmap.
Some other devices return a full size Bitmap when extras.get("data"); in onActivityResult. If the bitmap is too large that can result in an OutOfMemmoryError, so maybe you need to decode your image in a smaller size to not take so much memmory heap. This two links can help you in this situation:
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
BitmapFactory OOM driving me nuts
Maybe your activity is destroyed by the GC so you have to use onSavedInstanceState and onRestoreInstanceState to save your Activity's data. See the answer of this previous post for more information.
I don't know if you already have dealt with these issues.
Hope that helps:)
First, make sure to check request code, you might be catching someone else's result there. Second, don't use the intent's data Bitmap - if anything, it's small, but since you provide the path to store captured image, it shouldn't even be there (see here). So, store the url you provided as output file path and read Bitmap from there when you've received RESULT_OK for your request:
...
// save your file uri, not necessarily static
mUriSavedImage = Uri.fromFile(output);
startActivityForResult(camera, MY_REQUEST_CODE);
/* Make a String like "com.myname.MY_REQUEST_CODE" and hash it into int to give it
a bit of uniqueness */
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Bitmap bmp = BitmapFactory.decodeFile(mUriSavedImage);
if (bmp != null) {
image.setImageBitmap(bmp); // Set imageview to image that was
// captured
image.setScaleType(ScaleType.FIT_XY);
} else {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show();
}
}
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
For Samsung devices add below one line in your AndroidManifest.xml File
android:configChanges="orientation|screenSize"
i hope this will work for you
I faced the same issue. Apparently the fix is to make the uriSavedImage as static. Not sure if this is the best way. But this works for me.
Follow the steps given on this link. Hope this is useful for you.
OR
Fetching Your Image Without Crashing
Write the below code in MainActivity
// Storage for camera image URI components
private final static String CAPTURED_PHOTO_PATH_KEY = "mCurrentPhotoPath";
private final static String CAPTURED_PHOTO_URI_KEY = "mCapturedImageURI";
// Required for camera operations in order to save the image file on resume.
private String mCurrentPhotoPath = null;
private Uri mCapturedImageURI = null;
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
if (mCurrentPhotoPath != null) {
savedInstanceState.putString(CAPTURED_PHOTO_PATH_KEY, mCurrentPhotoPath);
}
if (mCapturedImageURI != null) {
savedInstanceState.putString(CAPTURED_PHOTO_URI_KEY, mCapturedImageURI.toString());
}
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState.containsKey(CAPTURED_PHOTO_PATH_KEY)) {
mCurrentPhotoPath = savedInstanceState.getString(CAPTURED_PHOTO_PATH_KEY);
}
if (savedInstanceState.containsKey(CAPTURED_PHOTO_URI_KEY)) {
mCapturedImageURI = Uri.parse(savedInstanceState.getString(CAPTURED_PHOTO_URI_KEY));
}
super.onRestoreInstanceState(savedInstanceState);
}
Hello all i know answer has been given but as this is also one of the easiest solution solution i have ever found
Here is an example, which is itself bothering about the device!
AndroidCameraUtils - Download the project and from library project by including it below is the code snippet you can use !
private void setupCameraIntentHelper() {
mCameraIntentHelper = new CameraIntentHelper(this, new CameraIntentHelperCallback() {
#Override
public void onPhotoUriFound(Date dateCameraIntentStarted, Uri photoUri, int rotateXDegrees) {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_found) + photoUri.toString());
Bitmap photo = BitmapHelper.readBitmap(CameraIntentActivity.this, photoUri);
if (photo != null) {
photo = BitmapHelper.shrinkBitmap(photo, 300, rotateXDegrees);
ImageView imageView = (ImageView) findViewById(de.ecotastic.android.camerautil.sample.R.id.activity_camera_intent_image_view);
imageView.setImageBitmap(photo);
}
}
#Override
public void deletePhotoWithUri(Uri photoUri) {
BitmapHelper.deleteImageWithUriIfExists(photoUri, CameraIntentActivity.this);
}
#Override
public void onSdCardNotMounted() {
Toast.makeText(getApplicationContext(), getString(R.string.error_sd_card_not_mounted), Toast.LENGTH_LONG).show();
}
#Override
public void onCanceled() {
Toast.makeText(getApplicationContext(), getString(R.string.warning_camera_intent_canceled), Toast.LENGTH_LONG).show();
}
#Override
public void onCouldNotTakePhoto() {
Toast.makeText(getApplicationContext(), getString(R.string.error_could_not_take_photo), Toast.LENGTH_LONG).show();
}
#Override
public void onPhotoUriNotFound() {
messageView.setText(getString(R.string.activity_camera_intent_photo_uri_not_found));
}
#Override
public void logException(Exception e) {
Toast.makeText(getApplicationContext(), getString(R.string.error_sth_went_wrong), Toast.LENGTH_LONG).show();
Log.d(getClass().getName(), e.getMessage());
}
});
}
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
mCameraIntentHelper.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mCameraIntentHelper.onRestoreInstanceState(savedInstanceState);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
mCameraIntentHelper.onActivityResult(requestCode, resultCode, intent);
}
}
NOTE:- I tried many examples for camera utils and ofcourse there are another ways to handle it but for beginners and person who are not too much familier with the core concepts would be more comfort with this project. THanks!
<!-- User features are request to enroll due to vivo solution for mobiles-->
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-feature android:name="android.hardware.camera.front" android:required="true" />
<uses-feature
android:name="android.hardware.camera.autofocus"
android:required="true"/>
<uses-feature android:name="android.hardware.microphone" />
<uses-feature
android:name="android.hardware.camera.any"
android:required="true"/>
<uses-feature
android:name="android.hardware.camera.flash"
android:required="true"/>
<!-- end User features are request to enroll due to vivo solution for mobiles-->