I inserted on my application a section to take and select pictures, but unfortunately, sometimes, when I take a photo or I select a picture to save on my server, the application crashes. Is really weird because my application only crashes sometimes.
I'm receiving this error:
ViewRootImpl #2 Surface is not valid.
How can I check if the photo is null and prevent my application from crashing?
My code:
private void selectImage() {
final CharSequence[] options = {"Take photo","My gallery","Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(PhotosActivity.this);
builder.setTitle("Adicionar foto!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("My gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Take photo")){
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("Cancel")) {
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(), "A sua imagem estará brevemente disponível.",
Toast.LENGTH_LONG).show();
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
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);
if (image_str != null) {
newtask = new saveImage();
newtask.execute(image_str,sessionid);
}
Toast.makeText(getBaseContext(), "A sua imagem estará brevemente disponível.",
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;
}
Logcat
06-21 15:42:42.890: E/HAWAII_EGL(1795): Destroying surface without
window
06-21 15:42:49.376: I/dalvikvm(2183): Could not find method
android.content.res.TypedArray.getChangingConfigurations, referenced
from method
android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
06-21 15:42:49.376: I/dalvikvm(2183): Could not find method
android.content.res.TypedArray.getType, referenced from method
android.support.v7.internal.widget.TintTypedArray.getType
Related
The onActivityResult() did not called when I select image from camera or gallery and my activity crashed, my code is below:
private void selectImage() {
final CharSequence[] options = { "cam", "gallery","cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(FragmentActivity4.this);
builder.setTitle("add");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=Utility.checkPermission(FragmentActivity4.this);
if (options[item].equals("cam"))
{
if(result){
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("gallery"))
{
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
startActivityForResult(chooserIntent, 2);
}
else if (options[item].equals("cancel")) {
ivImage.setImageDrawable(ContextCompat.getDrawable(FragmentActivity4.this, R.drawable.plusrred));
dialog.dismiss();
}
}
});
builder.show();
}
and in my onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode ==Activity.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);
ivImage.setImageBitmap(bitmap);
Bitmap bitmap1 = Bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.03), (int)(bitmap.getHeight()*0.03), true);
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.PNG, 0, baos1);
byte[] imgBytes = baos1.toByteArray();
base64String1 = Base64.encodeToString(imgBytes, Base64.DEFAULT);
String path = android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 0, 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();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = FragmentActivity4.this.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));
Log.w("path of image from gallery......******************.........", picturePath+"");
ivImage.setImageBitmap(thumbnail);
Bitmap thumbnail1 = Bitmap.createScaledBitmap(thumbnail,(int)(thumbnail.getWidth()*0.03), (int)(thumbnail.getHeight()*0.03), true);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumbnail1.compress(Bitmap.CompressFormat.PNG,0, baos);
byte[] imgBytes = baos.toByteArray();
base64String1 = Base64.encodeToString(imgBytes,
Base64.DEFAULT);
}
}
My activity extends AppCompatActivity.
Could you please tell me where is the problem?
Here you have
startActivityForResult(chooserIntent, 2);
and in your onActivityResult method you don't include 2 in your if statement. I think the problem is in that.
Your RequestCode is 2.
Change this:
if (requestCode == 1) {
With this:
if (requestCode == 2) {
I am trying to take photo and let the photo saved in portrait orientation. I could not do so even if I changed the manifest nor the intent's orientation to set it portrait. I Google and tried various ways, but none works. Please assist.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("request", requestCode + " result " + resultCode + " intent "
+ data);
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_SAVE_ITEM){
clearItemContents();
}
else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
{ExifInterface ei = new ExifInterface(cameraImagePath);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
switch(orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotateImage(bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotateImage(bitmap, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
break;
}
openGallery();
}
else{
if (gallery == true) {
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
imageArray = imageToByteArray(new File(picturePath));
setImagePicture(picturePath);
} else {
}
} else if (gallery == false) {
File file = new File(cameraImagePath);
if (file.exists()) {
imageArray = imageToByteArray(file);
setImagePicture(cameraImagePath);
} else {
}
} else {
this.finish();
startActivity(new Intent(this, DefectAdd.class));
}}
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels)
{
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap
.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = pixels;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
private byte[] imageToByteArray(File file) {
try {
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
byte[] bytes = bos.toByteArray();
return bytes;
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
private void setImagePicture(String photoPath) {
editTextItemPic.setVisibility(ImageView.GONE);
itemImage.setVisibility(ImageView.VISIBLE);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
itemImage.setRotation(90);
itemImage.setImageBitmap(bitmap);
}
public void showDialog() {
builder.setTitle("Choose Action!");
builder.setItems(dialogItems, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (item == 0) {
openGallery();
} else if(item == 1) {
openCamera();
}else{
imageArray = null;
editTextItemPic.setVisibility(ImageView.VISIBLE);
itemImage.setVisibility(ImageView.GONE);
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
public void openGallery() {
MaterialAddActivity.gallery = true;
Intent i = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, MaterialAddActivity.RESULT_LOAD_IMAGE);
}
public void openCamera() {
USE_CAMERA=1;
Intent cameraIntent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
private String appFolderCheckandCreate() {
String appFolderPath = "";
File externalStorage =Environment.getExternalStorageDirectory();
if (externalStorage.canWrite()) {
appFolderPath = "/storage/emulated/0/DCIM/Camera/";
File dir = new File(externalStorage+"/storage/emulated/0/DCIM/Camera/");
if (!dir.exists()) {
dir.mkdirs();
}
} else {
}
return appFolderPath;
}
#SuppressLint("SimpleDateFormat") private String getTimeStamp() {
final long timestamp = new Date().getTime();
final Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
final String timeString = new SimpleDateFormat("HH_mm_ss_SSS")
.format(cal.getTime());
return timeString;
}
public void saveImage()
{
File filename;
try
{
USE_CAMERA=0;
String path = Environment.getExternalStorageDirectory().toString();
new File(path + "/QSHelper").mkdirs();
filename = new File(path + "/QSHelper/image"+LASTINSERTEDID+".png");
FileOutputStream out = new FileOutputStream(filename);
photo.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(),
filename.getAbsolutePath(), filename.getName(),
filename.getName());
} catch (Exception e)
{
e.printStackTrace();
}
}
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 have made a demo to make a pic with the cam, save the image, and then, in other activity show the last pic made it. This is OK with the emulator, but when I install my demo in a real phone, I can make the pic, but the file size saved is O KB.
//This is the method where I make the photo
private boolean makePhoto(){
try{
ImageCaptureCallback camDemo = null;
SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");
String filenameTimeStamp = timeStampFormat.format(new Date());
ContentValues values = new ContentValues();
values.put(MediaColumns.TITLE, String.format("%s.jpg", filenameTimeStamp));
values.put(ImageColumns.DESCRIPTION, "Imagen desde Android Emulator");
Uri uri = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values);
Log.d("titulo: ", values.get(MediaColumns.TITLE).toString());
camDemo = new ImageCaptureCallback(getContentResolver().openOutputStream(uri));
this.camera.takePicture(this.mShutterCallback, this.mPictureCallback, camDemo);
Log.d("makePhoto", "Foto hecha");
return true;
}catch(Exception ex){
ex.printStackTrace();
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, ex.toString(), duration);
toast.show();
}
return false;
}
//This is the object where the pic taken is saved
public class ImageCaptureCallback implements PictureCallback {
private OutputStream fileoutputStream;
public ImageCaptureCallback(OutputStream fileoutputStream){
this.fileoutputStream = fileoutputStream;
}
public void onPictureTaken(byte[] data, Camera camera){
try{
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap myImage = BitmapFactory.decodeByteArray(data, 0, data.length,options);
BufferedOutputStream bos = new BufferedOutputStream(this.fileoutputStream);
myImage.compress(CompressFormat.JPEG, 75, bos);
bos.flush();
bos.close();
}catch (Exception ex){
ex.printStackTrace();
}
}
}
What happened?
I am sending you the code for taking picture and take the picture into your application.
First of all add the below intend:
File imageFile = new File(imageFilePath);
Uri imageFileUri = Uri.fromFile(imageFile);
Intent i = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(i, CAMERA_PIC_REQUEST);
And then add the below startActivityForResule in your code
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode)
{
case SELECT_PICTURE:
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
// file path of selected image
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourSelectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
encode = Base64.encodeBytes(byteArray);
try {
byte[] decode = Base64.decode(encode);
Bitmap bmp = BitmapFactory.decodeByteArray(decode, 0,
decode.length);
imgview_photo.setImageBitmap(bmp);
btn_getphoto.setVisibility(View.INVISIBLE);
btn_cancel.setVisibility(View.VISIBLE);
btn_upload.setVisibility(View.VISIBLE);
}
catch (IOException e) {
e.printStackTrace();
}
break;
case CAMERA_PIC_REQUEST:
Bitmap bmp = BitmapFactory.decodeFile(imageFilePath);
int width = bmp.getWidth();
int height = bmp.getHeight();
float scaleWidth = ((float) 300) / width;
float scaleHeight = ((float) 300) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, width,
height, matrix, true);
ByteArrayOutputStream baostream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, baostream);
byte[] byteArrays = baostream.toByteArray();
encode = Base64.encodeBytes(byteArrays);
try {
byte[] decode = Base64.decode(encode);
Bitmap bitmp = BitmapFactory.decodeByteArray(decode, 0,
decode.length);
imgview_photo.setImageBitmap(bitmp);
btn_getphoto.setVisibility(View.INVISIBLE);
btn_cancel.setVisibility(View.VISIBLE);
btn_upload.setVisibility(View.VISIBLE);
} catch (IOException e) {
e.printStackTrace();
}
}
}