In my code I allow user to upload photos from gallery or from camera. Then image is stored into the server through retrofit. When retrieved the photo is always rotated 90 degrees if the photo is taken using the phone's camera (regardless whether it is from invoked through the app or invoked through the camera directly). If the images are not taken using the camera, the orientation is correct. How do I resolve this?
I know if I tried to display the image directly without storing it in server, and it was possible to be in the right orientation because I could rotate it before displaying. I am doing something similar to the codes here: https://gist.github.com/Mariovc/f06e70ebe8ca52fbbbe2.
But because I need to upload to the server and then retrieve from the server again. How do I rotate it before storing to the server so that when I retrieve it, it is already in the right orientation?
Below is some parts of my codes (just some usual handling of images and displayAvatarInProfile() is called after the service finished the downloading of image):
public void displayAvatarInProfile(String filePath) {
if(filePath != null && filePath != ""){
int targetW = mProfilePicImageView.getWidth();
int targetH = mProfilePicImageView.getHeight();
Bitmap bm = ImageStorageUtils.resizePic(filePath, targetW, targetH);
mProfilePicImageView.setImageBitmap(bm);
} else {
mProfilePicImageView.setImageBitmap(null);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == Activity.RESULT_OK) {
Uri fileUri = null;
String filePath = null;
switch(requestCode) {
case REQUEST_PICK_IMAGE:
fileUri = data.getData();
break;
case REQUEST_CAPTURE_IMAGE:
File imageFile = ImageStorageUtils.getFile(
getActivity().getResources().getString(R.string.ApptTitle),
"avatar_" + mUser.getLogin());
filePath = imageFile.getAbsolutePath();
fileUri = ImageStorageUtils.getUriFromFilePath(mContext.get(), filePath);
break;
default:
break;
}
if(fileUri != null) {
getActivity().startService(ProfileService.makeIntentUploadAvatar(
mContext.get(), mUser.getId(), fileUri));
}
}
}
public void pickImage() {
final Intent imageGalleryIntent =
new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI)
.setType("image/*")
.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
// Verify the intent will resolve to an Activity.
if (imageGalleryIntent.resolveActivity(getActivity().getPackageManager()) != null)
// Start an Activity to get the Image from the Image Gallery
startActivityForResult(imageGalleryIntent,
DisplayProfileFragment.REQUEST_PICK_IMAGE);
}
public void captureImage() {
Uri captureImageUri = null;
try {
captureImageUri = Uri.fromFile(ImageStorageUtils.createImageFile(
mContext.get(),
getActivity().getResources().getString(R.string.ApptTitle),
"avatar_" + mUser.getLogin()));
} catch (IOException e) {
e.printStackTrace();
}
// Create an intent that will start an Activity to get
// capture an image.
final Intent captureImageIntent =
new Intent(MediaStore.ACTION_IMAGE_CAPTURE)
.putExtra(MediaStore.EXTRA_OUTPUT, captureImageUri);
// Verify the intent will resolve to an Activity.
if (captureImageIntent.resolveActivity(getActivity().getPackageManager()) != null)
// Start an Activity to capture an image
startActivityForResult(captureImageIntent,
DisplayProfileFragment.REQUEST_CAPTURE_IMAGE);
}
Update 1
Was commented that I needed more description:
When I am uploading a file, I do this:
boolean succeeded = mImpatientServiceProxy.uploadAvatar(userId, new TypedFile("image/jpg", imageFile));
When I download, I get a retrofit.client.Response object, which I then get the InputStream from the Response and write the data to a file using an Output Stream.
final InputStream inputStream = response.getBody().in();
final OutputStream outputStream = new FileOutputStream(file);
IOUtils.copy(inputStream, outputStream);
Update 2
This is not a duplicate of existing solution because the user can upload from gallery, you do not know if it is a photo taken from resources online or from camera, so you cannot rotate the image when you display it.
Use camera api instead of intent. When you capture image using intents it displays rotated. In camera api there are methods by which you can change the rotation of the camera as well as the captured photo too.
Related
I am trying to make an app that takes a picture and embed another image like a logo onto the original image. But I have a problem in the initial stages.
I am trying to save the image from the Bitmap received from onActivityResult for the camera intent. But after using the following code, the images are scaled-down and compressed too much and looks bad. Can someone help me retain the picture quality and size?
Here are the pictures that the app saved:
public void saveBitmapToGallery(Bitmap bm,String picturename){
String root = Environment.getExternalStorageDirectory().toString();
File mydir = new File(picturepath);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
displayheight = dm.heightPixels;
displaywidth = dm.widthPixels;
File file = new File(mydir, picturename+".JPG");
try {
FileOutputStream fos = new FileOutputStream(file);
bm.createScaledBitmap(bm,displaywidth,displayheight,true);
bm.compress(Bitmap.CompressFormat.JPEG,100, fos);
fos.flush();
fos.close();
}catch (FileNotFoundException e){
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
}
I expect an image like the general camera app so that I can work on embedding the logo once I can get my app to save good quality images.
the image did not convert into byte output
also, Go for My Github Profile for this
https://github.com/axarlotwala/CafeDelearenter code here
// using intent open file chooser option
private void ShowFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE_REQUEST);
}
// show selected and path image in imageview
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
PATH = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(),PATH);
cat_image.setImageBitmap(bitmap);
tv_path.setText("Path : " .concat(GetPath(PATH)));
} catch (IOException e) {
e.printStackTrace();
}
}
//get correct path of image
private String GetPath(Uri uri){
String result;
Cursor cursor = getActivity().getContentResolver().query(uri,null,null,null,null);
if (cursor == null){
result = uri.getPath();
}else {
cursor.moveToFirst();
int id = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
result = cursor.getString(id);
cursor.close();
}
return result;
}
Well, I figured out what was wrong with the output image. We need to use EXTRA_OUTPUT for the picture to be saved in full size, otherwise only a thumbnail is saved.
Here is what we need to to before starting camera activity for result
if (picturefile != null) {
Uri pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() +
".provider", picturefile);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri); //This makes the image to save in full rather than just a low quality scaled-down thumbnail.
}
startActivityForResult(imageIntent, REQUEST_IMAGE_CAPTURE);
In an app I am allowing user to pick image from gallery or he can choose from camera. Though I can manage the image and show it in the activity in the first time, after closing the app and restarting it, the image is gone and the space is blank.There was an explanation given to me to save the image data in sharedPreferences but I am new in android and don't pretty much understand. I looked for sharedPreferences but don't know how to make it work.
So if anybody help kindly with some explanation and code, it would help me a lot.
Thanks.
Here is what I tried to do.
private void openCamera(){
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,getPhotoFileUri(photoFileName)); // set the image file name
// If you call startActivityForResult() using an intent that no app can handle, your app will crash.
// So as long as the result is not null, it's safe to use the intent.
if (intent.resolveActivity(getPackageManager()) != null) {
// Start the image capture intent to take photo
startActivityForResult(intent, TAKE_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// final android.widget.LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) imageview.getLayoutParams();
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
imageview.setImageURI(imageUri);
//selectedImagePath = getPath(imageUri);
//ystem.out.println("Image Path : " + selectedImagePath);
}
else if (requestCode == TAKE_IMAGE && resultCode == Activity.RESULT_OK) {
Uri takenPhotoUri = getPhotoFileUri(photoFileName);
// by this point we have the camera photo on disk
Bitmap rawTakenImage = BitmapFactory.decodeFile(takenPhotoUri.getPath());
// RESIZE BITMAP, see section below
// See BitmapScaler.java: https://gist.github.com/nesquena/3885707fd3773c09f1bb
// Get height or width of screen at runtime
int screenWidth = DeviceDimensionsHelper.getDisplayWidth(this);
// Resize a Bitmap maintaining aspect ratio based on screen width
Bitmap resizedBitmap = BitmapScaler.scaleToFitWidth(rawTakenImage,screenWidth);
// Load the taken image into a preview
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// Compress the image further
resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
// Create a new file for the resized bitmap (`getPhotoFileUri` defined above)
Uri resizedUri = getPhotoFileUri(photoFileName + "_resized");
File resizedFile = new File(resizedUri.getPath());
// Write the bytes of the bitmap to file
try{
resizedFile.createNewFile();
FileOutputStream fos = new FileOutputStream(resizedFile);
fos.write(bytes.toByteArray());
fos.close();
}catch (IOException e){
System.out.println("Error occured");
}
imageview.setImageBitmap(rawTakenImage);
}
}
public Uri getPhotoFileUri(String fileName) {
// Only continue if the SD Card is mounted
if (isExternalStorageAvailable()) {
// Get safe storage directory for photos
// Use `getExternalFilesDir` on Context to access package-specific directories.
// This way, we don't need to request external read/write runtime permissions.
File mediaStorageDir = new File(
getExternalFilesDir(Environment.DIRECTORY_PICTURES), APP_TAG);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()){
Log.d(APP_TAG, "failed to create directory");
}
// Return the file target for the photo based on filename
return Uri.fromFile(new File(mediaStorageDir.getPath() + File.separator + fileName));
}
return null;
}
// Returns true if external storage for photos is available
private boolean isExternalStorageAvailable() {
String state = Environment.getExternalStorageState();
return state.equals(Environment.MEDIA_MOUNTED);
}
You can use below ways to store image.
1. Database with Base64
You can convert image into base64 string and store in database.
So when you open application you can retrieve base64 String from database and display image in ImageView.
2. Store Image Path in Database
You can store image path in database, when you open application, just retrieve image path and display image in ImageView.
But if you delete image from memory, you will not get image from iamge path.
3. Store Image in Server.
If you store image in server, you can retrieve image path and download image using AsyncTask or sime 3rd party liberary. And display image in ImageView.
(Liberaries : Picaso, LazyLoading etc.)
I am trying to use default camera with Intent for both image and video capture.
when i turn to front camera and capture the image or video preview (captured image or video ) is inverted . So now I want to put preScale in frontCamera. But didn't know where to find Camera ID in default Camera.!!
Note : this is not Custom Camera.!!
Problem is : Captured Image from Front camera getting image is mirror image. Look into it if there any problem ? I didnt get ! Thx
Even stored captured image in SDCard also mirror image! Now how to preScale or any other idea to correct iT??
Help!
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
CatureImage method
private void captureImage() {
Context context = this;
PackageManager packageManager = context.getPackageManager();
if (packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA) == false
&& packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY) == false) {
Toast.makeText(CameraRolling2.this, "camera not available'",
Toast.LENGTH_SHORT).show();
return;
}
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent
.resolveActivity(CameraRolling2.this.getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Toast.makeText(CameraRolling2.this, "Error connecting camera",
Toast.LENGTH_SHORT).show();
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent,
CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
showImg.setImageBitmap(null);
}
}
}
#SuppressLint("SimpleDateFormat")
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(imageFileName, ".jpg", storageDir);
mCurrentPhotoPath = image.getAbsolutePath();
Log.v("createImageFile", "" + mCurrentPhotoPath);
return image;
}
and My Activity Result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE
&& resultCode == Activity.RESULT_OK) {
File imgFile = new File(mCurrentPhotoPath);
if (imgFile.exists()) {
BitmapFactory.Options bitmap_options = new BitmapFactory.Options();
bitmap_options.inSampleSize = 4;
bitmap_options.outHeight = 200;
bitmap_options.outWidth = 200;
Bitmap myBitmap = BitmapFactory.decodeFile(
imgFile.getAbsolutePath(), bitmap_options);
showImg.setImageBitmap(myBitmap);
if (showImg.getDrawable() == null) {
Log.e("IMAGEVIEW", "NULL IMAGE");
imageflag = false;
} else {
Log.e("IMAGEVIEW", "IMAGE VIEW UPDATED");
imageflag = true;
}
}
}
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(CameraRolling2.this, "Camera option canceled",
Toast.LENGTH_SHORT).show();
imageflag = false;
}
I am trying to use default camera with Intent for both image and video capture
There is no single "default camera with Intent" in Android. There are thousands of Android device models. These ship with hundreds of different "default camera with Intent" apps. Users can install other "default camera with Intent" apps from the Play Store or other places. Any one of those apps could be what the user chooses to use to take the picture (ACTION_IMAGE_CAPTURE) or record the video (ACTION_VIDEO_CAPTURE).
when i turn to front camera and capture the image or video preview (captured image or video ) is inverted
I am going to guess that by "inverted", you mean "rotated".
There are hundreds of different possible camera apps. Many will save the image or video with metadata that tells the viewer app to rotate the image (e.g., JPEG photos might have an orientation EXIF header). Some will not, electing to rotate the content themselves.
Also, the images or videos from any camera (front-facing, rear-facing, external) could be rotated.
Hence, you should not be assuming that the rotation is tied to the particular camera that the user used. Instead, examine the actual content and react accordingly. This sample project demonstrates this for rotating a JPEG image, using a couple of different techniques.
So now I want to put preScale in frontCamera.
You cannot control this.
But didn't know where to find Camera ID in default Camera.!!
You cannot control this.
I am having a problem while trying to save a photo to storage with an Android app. The app uses the devices camera to take a photo and save it as a PNG to the device.
For some reason no matter what I do or where I store the image the quality is very poor. The app is an existing project that is quite large so I was wondering if there are other factors to consider when saving images to a device or maybe another way of overriding the quality.
This is the function that was coded by the previous dev:
public String saveImageToDevice(Bitmap image) {
saveCanvasImage(image);
String root = Environment.getExternalStorageDirectory().toString()+"/Android/data/com.app.android";
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fname = "Image-"+ timeStamp +".png";
File file = new File (myDir, fname);
if (file.exists ()){
file.delete ();
}
try {
Toast.makeText(getActivity(), "Saving Image...", Toast.LENGTH_SHORT).show();
Log.i("Image saved", root+"/saved_images/"+fname);
FileOutputStream out = new FileOutputStream(file);
image.compress(CompressFormat.PNG, 100, out);
imageLocations.add(fname);
out.flush();
out.close();
//return myDir.getAbsolutePath() + "/" +fname;
return fname;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
And this is a function I have tried myself from an example online:
public void saveCanvasImage(Bitmap b) {
File f = new File(Environment.getExternalStorageDirectory().toString() + "/img.png");
try {
f.createNewFile(); // your mistake was at here
FileOutputStream fos = new FileOutputStream(f);
b.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
Both of these produce the same very poor images. I have posted a before and after segment below.
This is what the camera preview looks like.
This is the resulting image once it has saved.
After speaking to a few people i am including my camera intent code:
public void startCameraIntent(){
/*************************** Camera Intent Start ************************/
// Define the file-name to save photo taken by Camera activity
String fileName = "Camera_Example.png";
// Create parameters for Intent with filename
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
// imageUri is the current activity attribute, define and save it for later usage
#SuppressWarnings("unused")
Uri imageUri = getActivity().getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
/**** EXTERNAL_CONTENT_URI : style URI for the "primary" external storage volume. ****/
// Standard Intent action that can be sent to have the camera
// application capture an image and return it.
Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
//intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // set the image file name
startActivityForResult( intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
/*************************** Camera Intent End ************************/
}
As you can see the EXTRA_OUTPUT line is has been commented out due to it causing crashes with the below error:
12-17 13:31:37.339: E/AndroidRuntime(16123): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=65537, result=-1, data=null} to activity {}: java.lang.NullPointerException
I have also included my onActivityresult code too:
public void onActivityResult( int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
int page = mViewPager.getCurrentItem();
NotesPagerFragment note = pages.get(page);
Log.i("Request Code", ""+requestCode);
//For the ImageCapture Activity
if ( requestCode == 1) {
if ( resultCode != 0) {
/*********** Load Captured Image And Data Start ****************/
Bitmap bp = (Bitmap) data.getExtras().get("data");
//add the image to the note through a function call
note.addImage(bp);
note.saveImageToDevice(bp);
//String imageId = convertImageUriToFile( imageUri,CameraActivity);
// Create and excecute AsyncTask to load capture image
// new LoadImagesFromSDCard().execute(""+imageId);
/*********** Load Captured Image And Data End ****************/
} else if ( resultCode == 0) {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
}
}
//For the deleting an Image
if (requestCode == 2) {
String location = (String) data.getExtras().get("imageLocation");
if(data.getExtras().get("back") != null){
//just going back, don't mind me
}else {
//Toast.makeText(this.getActivity(), "BOO", Toast.LENGTH_SHORT).show();
note.removeNoteImageFromView(location);
database.removeSingleNoteImageFromSystemByLocation(location);
}
}
}
OK so after a lot of help from MelquiadesI have eventually solved this issue. The problem I had was that my intent and onActivityResult were retrieving the thumbnail of the image and scaling it up (hence the poor quality).
The line below is responsible for getting the thumbnail preview (120px x 160px):
Bitmap bp = (Bitmap) data.getExtras().get("data");
In order to access the full image I need to add EXTRA_OUTPUT to the intent which looks as follows:
public void startCameraIntent(){
/*************************** Camera Intent Start ************************/
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile); // convert path to Uri
// Standard Intent action that can be sent to have the camera
// application capture an image and return it.
Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri); // set the image file name
startActivityForResult( intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
/*************************** Camera Intent End ************************/
}
I also declared my imageFilePath as a string at the top of my activity:
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFilePath = Environment.getExternalStorageDirectory().toString()+"/Android/data/com.my.app/Image-"+timeStamp+".png";
I then had to change onActivityResult so it could access the full image to use:
public void onActivityResult( int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
int page = mViewPager.getCurrentItem();
NotesPagerFragment note = pages.get(page);
Log.i("Request Code", ""+requestCode);
//For the ImageCapture Activity
if ( requestCode == 1) {
if ( resultCode != 0) {
/*********** Load Captured Image And Data Start ****************/
// Decode it for real
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = false;
//imageFilePath image path which you pass with intent
Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
//rotate image by 90 degrees
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
//add the image to the note through a function call
note.addImage(rotatedBitmap);
note.saveImageToDevice(rotatedBitmap);
//String imageId = convertImageUriToFile( imageUri,CameraActivity);
// Create and excecute AsyncTask to load capture image
// new LoadImagesFromSDCard().execute(""+imageId);
/*********** Load Captured Image And Data End ****************/
} else if ( resultCode == 0) {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this.getActivity(), " Picture was not taken ", Toast.LENGTH_SHORT).show();
}
}
//For the deleting an Image
if (requestCode == 2) {
String location = (String) data.getExtras().get("imageLocation");
if(data.getExtras().get("back") != null){
//just going back, don't mind me
}else {
//Toast.makeText(this.getActivity(), "BOO", Toast.LENGTH_SHORT).show();
note.removeNoteImageFromView(location);
database.removeSingleNoteImageFromSystemByLocation(location);
}
}
}
The key part here is:
// Decode it for real
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = false;
//imageFilePath image path which you pass with intent
Bitmap bp = BitmapFactory.decodeFile(imageFilePath, bmpFactoryOptions);
This code decodes the image you saved at imageFilePath into a usable bitmap. From here you can use it as normal.
Sometimes (apparently this is quite common) the image comes in rotated by 90°, the next bit of code will rotate that back if you need it to:
//rotate image by 90 degrees
Matrix rotateMatrix = new Matrix();
rotateMatrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bp, 0, 0, bp.getWidth(), bp.getHeight(), rotateMatrix, false);
I am using android inbuilt camera to take picture and then attaching the same picture to email, when i am testing this functionality in 1.6 device, i am able name the picture that to be taken by in built camera, but in 2.1, the picture is having a name i.e given by device,
How to give user defined name in 2.1 inbuilt camera images..
to avoid that problem i am saving the image manually but when i try to get the image back through intent as bitmap and then saving it to sd card using compress method
this methods handles result from inbuilt camera
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
File file = new File(Environment.getExternalStorageDirectory()
+ "/test.png");
switch (requestCode)
{
case PHOTO_ACTION:
if (resultCode == RESULT_CANCELED)
{
addPhoto = false;
Toast.makeText(this, "Canceled ", Toast.LENGTH_LONG).show();
break;
} else if (resultCode == RESULT_OK)
{
Bundle b = data.getExtras();
Bitmap bm = (Bitmap) b.get("data");
FileOutputStream out;
try
{
out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
scanPhoto(file.toString());
out = null;
addPhoto = true;
} catch (Exception e)
{
e.printStackTrace();
addPhoto = false;
}
but when i am storing like this i am getting two images. one with system given name and other with name given by me. but the image one which has user defined is having less resolution so i question is how to save the bitmap with more resolution with out compressing it ..
please help.... me
If you just want to save the bitmap without losing quality try using CompressFormat.PNG instead of JPEG, I've seen people having that problem before. Try changing:
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
with:
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
and see it it helps.
Apart from Rick answer above, make sure your are providing a URI to camera intent where it can save the full image, else it will return thumb image in data parameter of intent.
So it will be like:
Intent photoPickerIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
imgFile = new File("Cache directory","img.png"); //== where you want full size image
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(imgFile));
startActivityForResult(photoPickerIntent, PickPhoto);
This was the error that I was doing.