i have an ImageView in which Gallery selected images need to set but when i select camera folder images, selected image is not set in ImageView .
if (requestCode == REQUEST_PICK_IMAGE_FROM_GALLERY ) {
Uri selectedImg = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getActivity().getContentResolver().query(selectedImg, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
bitmap = BitmapFactory.decodeFile(picturePath,options);
mUserProfileImage.setImageBitmap(bitmap);
}
if(selectedImg!=null) { c = getActivity().getContentResolver().query(selectedImg, filePath, null, null, null); }else{ Toast.makeText(mContext,"This image does not exiest in device",Toast.LENGTH_SHORT).show(); return; } f = new File(picturePath);
mUserProfileImage.setImageBitmap(BitmapFactory.decodeFile(path,options));
// Call this after copied image , and delete then after
if (f != null) {
f.delete(); // previously i set f in imageView and already handled NPE, so no crash appeared.
}
I got the solution of problem, when i capture images from camera , it got stored in temp.png, and i copy this image to some other path and delete that temp.png, So when i again try to set the deleted image , it does not set and i handled the NEP also.
I debugged and corrected the code . :)
Bitmap realImage;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 5;
options.inPurgeable=true;
options.inInputShareable=true;
realImage = BitmapFactory.decodeByteArray(data,0,data.length,options);
ExifInterface exif = null;
try {
exif = new ExifInterface(path + c.getTime().getSeconds()
+ ".jpg");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Log.d("EXIF value",
exif.getAttribute(ExifInterface.TAG_ORIENTATION));
if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("1")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("8")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("3")) {
realImage = rotate(realImage, 90);
} else if (exif.getAttribute(ExifInterface.TAG_ORIENTATION)
.equalsIgnoreCase("0")) {
realImage = rotate(realImage, 90);
}
} catch (Exception e) {
}
image.setImageBitmap(realImage);
Related
I am attempting to upload an image from an android application to the server. I am calling the upload function and trying to get the image from ImageVeiw but no success. The image is set on the ImageVeiw from the gallery or camera.
Unable to get the file to send to the server
This is my code that I am using to set image from camera and gallery.
if(requestCode == CAMERA_REQUEST & resultCode == RESULT_OK){
Log.d("camera/gallery", "camera");
Bitmap photo = (Bitmap) data.getExtras().get("data");
profilePicture.setImageBitmap(photo);
} else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Log.d("camera/gallery", "gallery");
// get image from gallery
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver().query(selectedImage,filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap loadedBitmap = BitmapFactory.decodeFile(picturePath);
// check orientation of image and rotate if required
ExifInterface exifInterface = null;
try{
File pictureFile = new File(picturePath);
exifInterface = new ExifInterface(pictureFile.getAbsolutePath());
} catch (IOException e){
e.printStackTrace();
}
int orientation = exifInterface.ORIENTATION_NORMAL;
if(exifInterface != null){
orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
}
switch(orientation){
case ExifInterface.ORIENTATION_ROTATE_90:
loadedBitmap = rotateBitmap(loadedBitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
loadedBitmap = rotateBitmap(loadedBitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
loadedBitmap = rotateBitmap(loadedBitmap, 270);
break;
case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
loadedBitmap = flipBitmap(loadedBitmap, true, false);
case ExifInterface.ORIENTATION_FLIP_VERTICAL:
loadedBitmap = flipBitmap(loadedBitmap, false, true);
default:
loadedBitmap = loadedBitmap;
}
// set image to ImageView
profilePicture.setImageBitmap(loadedBitmap);
}
I am able to get the bitmap image and trying to save it to the file. I am later trying to retrieve the same file and upload it to the server using retrofit
I am getting this error from retrofit on failure
W/System.err: java.io.FileNotFoundException: file:/data/user/0/com.example.fileuploaddemo/files/cleaton_profile_20191023T111341.png (No such file or directory)
Code for storing and retrieving the file and send the image file
public void uploadProfileImage(){
Uri fileUri = getSelectedFile();
if(Uri.EMPTY.equals(fileUri)){
Toast.makeText(this, "Exception Occurred", Toast.LENGTH_SHORT).show();
} else {
File originalFile = FileUtils.getFile(fileUri.toString());
Log.d(TAG, "in upload"+originalFile.getAbsolutePath());
RequestBody filePart = RequestBody.create(MediaType.parse("image/*"), originalFile);
MultipartBody.Part file = MultipartBody.Part.createFormData("upload", originalFile.getName(), filePart);
RequestBody modePart = RequestBody.create(MultipartBody.FORM, "profilepicture");
APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
apiInterface.uploadPhoto(file, modePart).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, "Upload Fail", Toast.LENGTH_SHORT).show();
t.printStackTrace();
}
});
}
}
public Uri getSelectedFile(){
try{
String username = "cleaton";
// get bitmap from image set on imageview and convert to byte array
BitmapDrawable bitmapDrawable = (BitmapDrawable) profilePicture.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
byte[] bitmapdata = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
String timeStamp = dateFormat.format(new Date());
File file = new File(getFilesDir(), username+"_profile_"+timeStamp+".png");
// insert byte array into file output stream with name
FileOutputStream fileOutputStream = openFileOutput(username+"_profile_"+timeStamp+".png", MODE_PRIVATE);
fileOutputStream.write(bitmapdata);
fileOutputStream.flush();
fileOutputStream.close();
File profileImageFile = new File(file.getAbsolutePath());
Log.d(TAG, "file retrieve"+profileImageFile);
Uri fileUri = Uri.fromFile(profileImageFile);
Log.d(TAG, "file Uri"+fileUri);
return fileUri;
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
return null;
}
catch(IOException ioe){
ioe.printStackTrace();
return null;
}
}
To expound on Webfreak's answer:
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Once the Bitmap is retrieved, you can create a byte stream from which you can read the bytes and send those to your network socket by using a method similar to those below. Without knowing your upload method I am not sure if this is sufficient.
private InputStream getBitmapInputStream(BitmapFactory.Options options,
Bitmap bitmap) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(getCompressionFormat(options), 100 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
return new ByteArrayInputStream(bitmapdata);
}
private Bitmap.CompressFormat getCompressionFormat(BitmapFactory.Options options) {
if (options == null || options.outMimeType == null) return Bitmap.CompressFormat.JPEG;
if (options.outMimeType.endsWith("/png")) {
return Bitmap.CompressFormat.PNG;
} else if (options.outMimeType.endsWith("/webp")) {
return Bitmap.CompressFormat.WEBP;
} else {
return Bitmap.CompressFormat.JPEG;
}
}
Fist you need to get the bitmap from Imageview:
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = drawable.getBitmap();
Once you have bitmap, you can upload it to server.
i am not able to store the path and image into database, i want to store path or image into database and i want to fetch that image and set to imageview after updating profile..here is my onactvity result please help me.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
ImagePaht = CommonUtility.encodeTobase64(bitmap);
mAddProfilePic.setImageBitmap(bitmap);
mAddProfilePic.setScaleType(ImageView.ScaleType.MATRIX);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
boolean delete = f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byteArray = stream.toByteArray();
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
if (c != null) {
c.moveToFirst();
}
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
// Log.e("path of ", picturePath + "");
ImagePaht = CommonUtility.encodeTobase64(thumbnail);
mAddProfilePic.setImageBitmap(thumbnail);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
mAddProfilePic.setScaleType(ImageView.ScaleType.MATRIX);
}
}
}
//this my method to save in database
private void saveInDbHospitalTable() {
Log.e("file name", "" + ImagePaht);
Table_Hospital_Methods mTable_Hospital_Methods = new Table_Hospital_Methods(getApplicationContext());
//String profilePictureURL = String.valueOf(byteArray);
// Log.e("profilePictureURL", "" + profilePictureURL);
String hospitalName = mHospitalName.getText().toString();
String doctorName = mDocName.getText().toString();
String registrationNo = mRegistrationNumber.getText().toString();
String hospitalPhoneNumber = mHospitalPhoneNumber.getText().toString();
String doctorPhoneNumber = mDoctorPhoneNumber.getText().toString();
String hospitalAddress = mHospiatlAddress.getText().toString();
ModelHospitalProfile modelHospitalProfile = new ModelHospitalProfile(byteArray, hospitalName,
doctorName, registrationNo, hospitalPhoneNumber, doctorPhoneNumber, hospitalAddress);
long hospitalId= mTable_Hospital_Methods.gethospitalId();
Log.e("hospitalId", "" + hospitalId);
if(mTable_Hospital_Methods.getHospitalCount()>0 && userName1==1) {
mTable_Hospital_Methods.updateToDo(modelHospitalProfile,hospitalId);
Log.e("update", "update");
}
else{
mTable_Hospital_Methods.insertHospital(modelHospitalProfile);}
}
For storing image into your database, you can either save image path or can save Base64 image into your database
Here, we are storing image path into database
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
settingImaePath(fileUri);
}
}
if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
Log.i("file path", "" + filePath);
final Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
File imageFile = null;
String mPath = null;
try {
// image naming and path to include sd card appending name you choose for file
mPath = Environment.getExternalStorageDirectory().toString() + "/" + now.getTime() + ".jpg";
imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
UserProfile userProfile = new UserProfile();
userProfile.setImagePath(mPath);
ProfileTable.getInstance().add(signupBean); // Here setting gallery image path into ProfileTable
userImage.setImageBitmap(bitmap); // userImage is an Imageview
} catch (IOException e) {
e.printStackTrace();
}
}
public void settingImaePath(Uri fileUri) {
String filePath = fileUri.getPath();
if (filePath != null) {
// Displaying the image or video on the screen
previewMedia(filePath);
}
}
private void previewMedia(String filePath) {
// Checking whether captured media is image or video
Log.i("file path", "" + filePath);
// bimatp factory
BitmapFactory.Options options = new BitmapFactory.Options();
// down sizing image as it throw s OutOfMemory Exception for larger
// images
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
File imageFile = null;
String mPath = null;
try {
// image naming and path to include sd card appending name you choose for file
mPath = Environment.getExternalStorageDirectory().toString() + "/" + now.getTime() + ".jpg";
imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 80;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
UserProfile userProfile = new UserProfile();
userProfile.setImagePath(mPath);
ProfileTable.getInstance().add(signupBean); // Here setting gallery image path into ProfileTable
userImage.setImageBitmap(bitmap);
}
//For Viewing save image from path
final Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imageView.setImageBitmap(bitmap);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == getActivity().RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
String wholeID = DocumentsContract.getDocumentId(filePath);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
uploadFilePath = cursor.getString(columnIndex);
uploadFilePath = decodeFile(uploadFilePath, 512, 512);
}
cursor.close();
try {
bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
if(sendImageType.equals("profile")){
imgProfile.setImageBitmap(bitmap);
}
else if(sendImageType.equals("cover")){
imgCover.setImageBitmap(bitmap);
}
pDialog = ProgressDialog.show(getActivity(), "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
uploadFile(uploadFilePath);
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Decode File :
private String decodeFile(String path,int DESIREDWIDTH, int DESIREDHEIGHT) {
String strMyImagePath = null;
Bitmap scaledBitmap = null;
try {
// Part 1: Decode image
Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, DESIREDWIDTH, DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);
if (!(unscaledBitmap.getWidth() <= DESIREDWIDTH && unscaledBitmap.getHeight() <= DESIREDHEIGHT)) {
// Part 2: Scale image
scaledBitmap = ScalingUtilities.createScaledBitmap(unscaledBitmap, DESIREDWIDTH, DESIREDHEIGHT, ScalingUtilities.ScalingLogic.FIT);
} else {
unscaledBitmap.recycle();
return path;
}
// Store to tmp file
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/TMMFOLDER");
if (!mFolder.exists()) {
mFolder.mkdir();
}
String s = "tmp.png";
File f = new File(mFolder.getAbsolutePath(), s);
strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
scaledBitmap.recycle();
} catch (Throwable e) {
}
if (strMyImagePath == null) {
return path;
}
return strMyImagePath;
}
Hi, i have an image uploader, i am uploading image from android gallery to my server. But some photos load horizontally. How can i understand, photo is horizontal or vertical and how do i rotate.
It look below, after upload :
to check the orientation of an image
ExifInterface ei = new ExifInterface(photoPath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
break;
case ExifInterface.ORIENTATION_ROTATE_180:
break;
// etc.
}
To rotate the image use
private Bitmap rotateImage(Bitmap source, float angle) {
Bitmap bitmap = null;
Matrix matrix = new Matrix();
matrix.postRotate(angle);
try {
bitmap = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(),
matrix, true);
} catch (OutOfMemoryError err) {
err.printStackTrace();
}
return bitmap;
}
try this code:
public static Bitmap getOriententionBitmap(String filePath){
Bitmap myBitmap = null;
try
{
File f = new File(filePath);
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(angle);
Bitmap bmp1 = BitmapFactory.decodeStream(new FileInputStream(f), null, null);
myBitmap = Bitmap.createBitmap(bmp1, 0, 0, bmp1.getWidth(), bmp1.getHeight(), mat, true);
}
catch (IOException e) {
Log.w("TAG", "-- Error in setting image");
}
catch(OutOfMemoryError oom) {
Log.w("TAG", "-- OOM Error in setting image");
}
return myBitmap;
}
I built an activity to take and choose pictures from gallery. I tried to run my App on three different devices, Samsung, Sony and ZTE.
The samsung device is the only device that crashes sometimes, and the error that I'm getting is:
Destroying surface without window.
This message says everything, samsung automatically destroys the surface when I open the camera or gallery, and when I try to go back to my activity, the application crashes because my surface doesn't exists anymore.
I'm trying to fix this error, Thats my function:
private void selectImage() {
final CharSequence[] options = {
translate.translation(language, 27), translate.translation(language, 28), translate.translation(language, 19)
};
AlertDialog.Builder builder = new AlertDialog.Builder(PhotosActivity.this);
builder.setTitle(translate.translation(language, 26));
builder.setItems(options, new DialogInterface.OnClickListener() {#Override
public void onClick(DialogInterface dialog, int item) {
//take picture
if (options[item].equals(translate.translation(language, 28))) {
Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
//gallery
} else if
(options[item].equals(translate.translation(language, 27))) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals(translate.translation(language, 19))) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp: f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
if (bitmap.getWidth() > bitmap.getHeight()) {
Matrix matrix = new Matrix();
matrix.postRotate(getExifOrientation(f.getAbsolutePath()));
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
int nh = (int)(bitmap.getHeight() * (612.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 612, nh, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
scaled.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte[] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
newtask = new saveImage();
newtask.execute(image_str, sessionid);
Toast.makeText(getBaseContext(), translate.translation(language, 29),
Toast.LENGTH_LONG).show();
String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
f.delete();
Log.e("", path);
FileOutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {
MediaStore.Images.Media.DATA
};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
if (thumbnail.getWidth() > thumbnail.getHeight()) {
Matrix matrix = new Matrix();
matrix.postRotate(getExifOrientation(picturePath));
thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
}
int nh = (int)(thumbnail.getHeight() * (612.0 / thumbnail.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(thumbnail, 612, nh, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
scaled.compress(Bitmap.CompressFormat.JPEG, 90, stream);
byte[] byte_arr = stream.toByteArray();
String image_str = Base64.encodeBytes(byte_arr);
newtask = new saveImage();
newtask.execute(image_str, sessionid);
Toast.makeText(getBaseContext(), translate.translation(language, 29),
Toast.LENGTH_LONG).show();
}
}
}
public static int getExifOrientation(String filepath) {
int degree = 0;
ExifInterface exif = null;
try {
exif = new ExifInterface(filepath);
} catch (IOException ex) {
ex.printStackTrace();
}
if (exif != null) {
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
if (orientation != -1) {
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
}
}
return degree;
}
}
Thanks.
I want to add image capturing in my Android app where user can captures images, I'm using the following code:
public void open_camera() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
try {
// place where to store camera taken picture
photo = this.createTemporaryFile("picture", ".jpg");
photo.delete();
} catch(Exception e) {
Toast.makeText(this, "Please check SD card! Image shot is impossible!", 10000);
}
mImageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
//start camera intent
startActivityForResult(intent,SELECT_PICTURE_CAMERA );
//Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//startActivityForResult(cameraIntent, SELECT_PICTURE_CAMERA);
}
private File createTemporaryFile(String part, String ext) throws Exception {
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
if(!tempDir.exists()) {
tempDir.mkdir();
}
return File.createTempFile(part, ext, tempDir);
}
When I retrieve
case SELECT_PICTURE_CAMERA:
if(resultCode == RESULT_OK) {
// Toast.makeText(this,"Camera" + imageReturnedIntent.getStringExtra(ZBarConstants.SCAN_RESULT), Toast.LENGTH_LONG).show();
//this.yourSelectedImage = (Bitmap) imageReturnedIntent.getExtras().get("data");
/*
ImageButton imgbtn = (ImageButton) findViewById(R.id.imageButton_Photo);
BitmapDrawable background = new BitmapDrawable(this.yourSelectedImage);
imgbtn.setBackgroundDrawable(background);
*/
try {
File f=new File(mImageUri.getPath());
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int angle = 0;
if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
angle = 90;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
angle = 180;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
angle = 270;
}
Matrix mat = new Matrix();
mat.postRotate(90);
Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, null);
this.yourSelectedImage = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), mat, true);
} catch (IOException e) {
Log.w("TAG", "-- Error in setting image");
} catch(OutOfMemoryError oom) {
Log.w("TAG", "-- OOM Error in setting image");
}
But unfortunately after doing all this, still image is not of full size and it's always landscape.
You have a small mistake in code, after you get the angle the image should rotate you need to use this value in postRotate.
Please replace the line:
mat.postRotate(90);
with:
mat.postRotate(angle);
Hope I helped you :-)
Regards,
Woody.