Android change photo orientation for upload - android

I have found lots of solution to change photo orientation for DISPLAY, and succeeded. But now I need to upload that photo by using file.path. Is there anyway to directly change the photo orientation but not just display differently?
CustomMultiPartEntity multipartContent = new CustomMultiPartEntity(
new CustomMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
Constant.Process = (int) ((num / (float) totalSize11) * 100);}
});
multipartContent.addPart("key", new StringBody(Constant.Key));
multipartContent.addPart("userfile", new FileBody(new File(up.FilePath)));
httpPost.setEntity(multipartContent);
HttpResponse response1 = httpClient.execute(httpPost, httpContext);
response = EntityUtils.toString(response1.getEntity());
Something like that, I need to insert a FileBody by a FilePath into that 'multipartContent', then upload, is there anyway to upload a correct orientation photo??
Thank you very much!
EDIT: This is my onclick method to have camera, how can I add code to rotate image before it was saved?
public void onClick(View v) {
if (v == btn_camera) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newPicFile = "Miuzz"+ df.format(date) + ".jpg";
String outPath = "/sdcard/" + newPicFile;
File outFile = new File(outPath);
mUri = Uri.fromFile(outFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
startActivityForResult(cameraIntent, 1);
}
}

There is unfortunately no way of modifying the orientation of the photo file other other than to load the image, rotate it manually and re-save it in it's correct orientation.
See this question for some details on how to save the image once it's rotated: Android Rotate Picture before saving
Edit: Ok, so what you'll want to do is in your onActivityResult() method, load the image and rotate it as you already do. After rotating it, you should have a correctly orientated Bitmap object, then all you need to do is either overwrite your existing photo, or create a new file like this:
try {
FileOutputStream out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Also worth noting, is that if you decide to create a new file, be sure to delete it after your upload is complete otherwise you'll be unnecessarily filling up the user's internal storage.

Related

Android Bitmap.Compress saves image of Low Quality and Scaled down image

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);

Save to Gallery - Android

I've a strange (and oddly specific) issue with saving to the gallery on Android.
A bit of background: The app I'm developing needs to be able to save images to the gallery, which has been well discussed on here before. However, there's a specific requirement for this project which is I need to be able to tag it with a specific date/time.
I've tried several methods to get this to work correctly and so far the best I have is a workaround.
What I'm doing at the moment is generating the image, saving it to a file and setting the created date in the EXIF data. I then open the Google Photos app and it shows up in the gallery, showing the correct date and time and is in the correct place within the gallery.
The issue with this however, is that it doesn't automatically show in any other gallery software (for example, the OEM gallery apps that may be shipped with a given device), nor does it show if the Google Photos app is open at the time of saving; It must be closed and relaunched in order for it to show.
Now, if I run a media scan it ignores the EXIF data and the image shows up as the last image created.
Here's the code I'm currently using:
static class InsertImageObj{
public String url;
public long id;
}
public static InsertImageObj insertImage(Bitmap source,
String title, long time) {
String path = createDirectoryAndSaveFile(source, title, time);
String stringUrl = path;
InsertImageObj retVal = new InsertImageObj();
retVal.url = stringUrl;
return retVal;
}
private static String createDirectoryAndSaveFile(Bitmap imageToSave, String fileName, long dateTime) {
File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); //DCIM = Digital Camera Image. This is where camera photos go!
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, fileName);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
ExifInterface ei = new ExifInterface(file.getAbsolutePath());
ei.setAttribute(ExifInterface.TAG_DATETIME, convertToExifDateTime(dateTime));
ei.setAttribute(ExifInterface.TAG_DATETIME_ORIGINAL, convertToExifDateTime(dateTime));
ei.setAttribute(ExifInterface.TAG_DATETIME_DIGITIZED, convertToExifDateTime(dateTime));
ei.saveAttributes();
} catch (Exception e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
private static String convertToExifDateTime(long timestamp) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", Locale.getDefault());
return sdf.format(new Date(timestamp));
}
I've also tried running setLastModified on the file (which doesn't work, OS permissions or something or other) and using a MediaScannerConnection instance to scan the individual file once it has been saved. The latter, however causes the system to ignore the date/time tags in the Exif data.
I also tried inserting the image into the gallery via a ContentResolver instance and setting the DATE_ADDED and DATE_TAKEN fields, again to no avail.
Is there something really, really obvious I've missed here?
You need to save your image in the media store provider
Use this function
public static void imageToGallery(Context context, String fileName) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.DATA, fileName);
context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
So, after saving your image, call imageToGallery.
Images are only visible in gallery apps if they are added to the android-media-db.
You can ask MediaScannerConnection.scanFile(...) to add the new photo-file to the android-media-db.
On some androiddevices (but not on all) the mediascanner starts automatically.
Also note: you should save the new photo as ".../DCIM/myApp/myPhotoName.jpg" instead of ".../DCIM/myPhotoName.jpg"
Use this function. Its working for me!
private void galleryAddPic() {
File f = new File(imageFilePath);
try {
MediaStore.Images.Media.insertImage(getActivity().getContentResolver(),
f.getAbsolutePath(), f.getName(), null);
getActivity().sendBroadcast(new Intent(
Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(f)));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

how to use a bitmap taken by the camera through multiple activities in android?

I am making a photo app in which in the first activity the user takes a picture (he can see the picture in the ImageView), in the second activity he chooses with who to share the image,and in the 3rd activity he should be able to see the image again in a different ImageView than the first to add some data. I know how to move the bitmap from one activity to the next one by an intent, but how to do it if i want to send it to the 3rd activity of my user path? If i startActivity(intent) it will skip my second activity and if i don´t put it the 3rd activity is showing me an empty ImageView.. Can someone please help me in telling me ways of how to automatically load (without user interaction) this picture in the 1st and 3rd activity and some example?
I already being reading posts about how to convert to Base64 and load again, but their examples are using images already in the memory of the phone and in my case are pictures that were just taken by the user, so in principle i don´t know the name of the image file..
Thank a lot!
Add This Image In Your Custome Catch Folder
Like Make Your Folder in External or Internal Storage
Then Save Image that will capture by camera inside That Folder..
public static void SaveImagecatch(Bitmap finalBitmap) throws IOException {
File Folder = new File(Environment.getExternalStorageDirectory() + "/data/Catch");
if (Folder.mkdir()) {
nomediaFile = new File(Environment.getExternalStorageDirectory() + "/data/Catch/" + NOMEDIA);
if (!nomediaFile.exists()) {
nomediaFile.createNewFile();
}
}
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/data/Catch");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
Catch_uri = Uri.parse("file://" + myDir + "/" + fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Log.e("yes", "yes");
} catch (Exception e) {
e.printStackTrace();
Log.e("no", "no");
}
}
Then.. get Image From Uri path of Your saved Image.
Uri imageUri = Catch_uri;
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(),imageUri);
Imageview my_img_view = (Imageview ) findViewById (R.id.my_img_view);
my_img_view.setImageBitmap(bitmap);
This is Worked For Me.. I Hope This Will be Helpfull to you
Actually in second activity, you need to get Intent from first activity and do your work and then create new Intent and put your image into it, finally start third activity using new intent.
in second activity:
Intent firstToSecodeIntent = getIntent();
// some codes
Intent secondToThirdIntent = new Intent(this, ThirdActivity.class);
Intent.putExtra("image", /*your Image object*/);
startActivity(secondToThirdIntent);
in third activity:
Intent secondToThirdIntent = getIntent();
// get your image and set it into your imageView

How do you save an Image so it can be used later in another activity using Android?

I have a program which takes a picture and then stores it in the Gallery. Here is the code:
public void onPictureTaken(byte[] data, Camera camera) {
try {
SimpleDateFormat df = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
String name = "foto_" + df.format(new Date());
ContentValues werte = new ContentValues();
werte.put(MediaColumns.TITLE, name);
werte.put(ImageColumns.DESCRIPTION, "Aufgenommen mit CameraDemo");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI,
werte);
OutputStream ausgabe = getContentResolver().openOutputStream(uri);
ausgabe.write(data);
ausgabe.close();
camera.startPreview();
} catch (Exception ex) {
Log.d(TAG, ex.getMessage());
}
}
Now how can I call this image in another activity so that i can work with it there? I heard
you could save it in a bitmap but I didnt understandt how.
I know that im missing some basic programming skills but this would really help me out.
If you need more of the code just write it in the comments. Thx
I did not understand your code much but You should use Intent.putExtras method to pass bytes to new activity(http://developer.android.com/reference/android/content/Intent.html#putExtra%28java.lang.String,%20byte[]%29)
or simply save image to sdcard for later use

Android Display Camera Image In New Activity

So far I have my app taking a picture creating a new folder on the SD Card and saving the pictuers into the new folder.
I'm trying to get it so once the picture has been took it will display in a new Activity with two buttons that say "Use" or "Retake". So far the image saving is working perfectly fine but once the image has been took and it tries to open the new Activity it just stays on the camera Activity and shows the image which I cant use as it has a surfaceView onit.
In my LogCat I get the error "Oh, no reference" which is set to show if it can't find the picture, which is why im thinking it may be because I am not calling the picture from the correct place in my Punch.java.
So basiclly I am trying to once an image has been took the app to open a New Activity "Punch.java" and display the image that has just been took.
UPDATE Thanks to Lumis (code below has been updated)
Changed
intent.putExtra("filepath",uriSavedImage);
to
intent.putExtra("filepath",uriSavedImage.toString());
Which now opens the new Activity but still cannot see the image.
UPDATE 2 Punch.java
I have updated my Punch.java as with the new code if i change (myRef) to "/sdcard/Punch/image_0.jpg" I can see that image but I need it to referance to the image that was just taken with the camera which is something to do with this line I think intent.putExtra("filepath",uriSavedImage.toString());
Update 3
Nearly working perfectly now using intent.putExtra("filepath",Uri.parse(output.getAbsolutePath()).toString()); but for some reason it is still putting mnt/sdcard at the start it just needs to be sdcard/
Ok now working fine /mnt/sdcard is when the sdcard was mounted to the computer while i took the picture.
In my Camera Activity I have
PictureCallback myPictureCallback_JPG = new PictureCallback(){
public void onPictureTaken(byte[] arg0, Camera arg1) {
// TODO Auto-generated method stub
/*Bitmap bitmapPicture
= BitmapFactory.decodeByteArray(arg0, 0, arg0.length); */
int imageNum = 0;
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "Punch");
imagesFolder.mkdirs(); // <----
String fileName = "image_" + String.valueOf(imageNum) + ".jpg";
File output = new File(imagesFolder, fileName);
while (output.exists()){
imageNum++;
fileName = "image_" + String.valueOf(imageNum) + ".jpg";
output = new File(imagesFolder, fileName);
}
Uri uriSavedImage = Uri.fromFile(output);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream(uriSavedImage);
imageFileOS.write(arg0);
imageFileOS.flush();
imageFileOS.close();
Toast.makeText(AndroidCamera.this,
"Image saved",
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getBaseContext(), Punch.class);
intent.putExtra("filepath",uriSavedImage.toString());
//just using a request code of zero
int request=0;
startActivityForResult(intent,request);
}};
And my Punch.java which is the next Activity is:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.punch);
String myRef = this.getIntent().getStringExtra("filepath");
File imgFile = new File(myRef);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageView myImage = (ImageView) findViewById(R.id.imagepunch);
myImage.setImageBitmap(myBitmap);
}
}
}
I think it is the file path issue. You submitted your file path as URI but you are reading it in the viewer activity as a string.
Perhaps you neet to change this line into:
intent.putExtra("filepath",uriSavedImage.toString());
Or
intent.putExtra("filepath",Uri.parse(output.getAbsolutePath()).toString());
Different version of android may not work the same when it comes to file path, so you need to experiment using Uri.parse(fileStr) or String...
Just looking at your code and your approach, I think what you would typically see in this scenario is a new content handler registered so that it appears under the "Share" option of the camera / image library. This way, you are not getting involved in the use/retake logic which is essentially redundant for built-in Android functionality. Think of an app like Evernote or Picasa. You take a picture (or look one up that you took previously) and select "Share". One of the Share options, along with Picasa, Email, etc would be your app. That is how I would do it.

Categories

Resources