Is there any solution to use AQuery library of android for JSON parsing? Do give the code for it. Any solution that makes use of AQuery and no need to create JSONObject instance and to get object from there. Any direct solution for it, please do answer it with a sample of code.
-- Complete code for capturing image ,saving to SD card , pick from gallery,compress,rotate image,etc.. 200% working.
public class A extends AppCompatActivity implements View.OnClickListener, AsyncTaskCompleteListener {
private static final String IMAGE_DIRECTORY = "/idyme";
private static int MAX_IMAGE_DIMENSION = 200;
private final String TAG = "RegisterFragment";
private Button btnVerify, btnUploadImage;
private String ImgPath = null, filePath = null,
profileImageFilePath, profileImageData = null,imageVideoType = "", imageVideoPath = "";
private ImageView ivImage;
private AQuery aQuery;
private Uri uri = null;
private ImageOptions imageOptions;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vip_registration);
ivImage = (ImageView) findViewById(R.id.ivProfile);
aQuery = new AQuery(this);
imageOptions = new ImageOptions();
imageOptions.memCache = true;
imageOptions.fileCache = true;
imageOptions.fallback = R.drawable.userimage;
}
#Override
public void onClick(View v) {
// onRegisterButtonClick();
switch (v.getId()) {
case R.id.btnUploadImage:
showPictureDialog();
}
}
private void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle(getResources().getString(
R.string.dialog_chhose_photo));
String[] pictureDialogItems = {
getResources().getString(R.string.dialog_from_gallery),
getResources().getString(R.string.dialog_from_camera)};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
private void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, Constants.CHOOSE_PHOTO);
}
private void takePhotoFromCamera() {
Calendar cal = Calendar.getInstance();
File file = new File(Environment.getExternalStorageDirectory(),
(cal.getTimeInMillis() + ".jpg"));
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// uri = Uri.fromFile(file);
uri = getOutputMediaFileUri();
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cameraIntent, Constants.TAKE_PHOTO);
}
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
private String getRealPathFromURI(Uri contentURI) {
String result;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(contentURI, proj, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file
// path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == Constants.CHOOSE_PHOTO) {
if (data != null) {
Uri contentURI = data.getData();
profileImageData = getRealPathFromURI(contentURI);
// new AQuery(getApplicationContext()).id(ivMeme).image(
// profileImageData, imageOptions);
try {
String path = saveImage(scaleImage(this, contentURI));
imageVideoPath = path;
aQuery.id(R.id.ivProfile).image(
imageVideoPath, imageOptions);
} catch (IOException e) {
e.printStackTrace();
Utils.showToast("Failed", this);
}
}
} else if (requestCode == Constants.TAKE_PHOTO) {
// old
if (uri != null) {
profileImageFilePath = uri.getPath();
if (profileImageFilePath != null
&& profileImageFilePath.length() > 0) {
File myFile = new File(profileImageFilePath);
String path = saveImage(BitmapFactory
.decodeFile(profileImageFilePath));
imageVideoPath = path;
aQuery.id(R.id.ivProfile).image(
imageVideoPath, imageOptions);
} else {
Utils.showToast("Failed", this);
}
} else {
Utils.showToast("Failed", this);
}
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
AppLog.Log("TAG", "File Saved::-> " + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
private static File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY, "Oops! Failed create " + IMAGE_DIRECTORY
+ " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
return mediaFile;
}
public static Bitmap scaleImage(Context context, Uri photoUri)
throws IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = getOrientation(context, photoUri);
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
if (rotatedWidth > MAX_IMAGE_DIMENSION
|| rotatedHeight > MAX_IMAGE_DIMENSION) {
float widthRatio = ((float) rotatedWidth)
/ ((float) MAX_IMAGE_DIMENSION);
float heightRatio = ((float) rotatedHeight)
/ ((float) MAX_IMAGE_DIMENSION);
float maxRatio = Math.max(widthRatio, heightRatio);
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
srcBitmap = BitmapFactory.decodeStream(is, null, options);
} else {
srcBitmap = BitmapFactory.decodeStream(is);
}
is.close();
/*
* if the orientation is not 0 (or -1, which means we don't know), we
* have to do a rotation.
*/
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0,
srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);
}
String type = context.getContentResolver().getType(photoUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (type.equals("image/png")) {
srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
} else if (type.equals("image/jpg") || type.equals("image/jpeg")) {
srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
}
byte[] bMapArray = baos.toByteArray();
baos.close();
return BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
}
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[]{MediaStore.Images.ImageColumns.ORIENTATION},
null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
}
--After getting images send it to server , like this :
map.put(Constants.Params.PROFILEPICTURE, imageVideoPath);
// Log.d("image view", profileImageFilePath);
new MultiPartRequester(this, map,
AndyConstants.ServiceCode.VIP_USER_REGISTRATION, this);
-- Permission required :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
-- dependencies :
compile files('libs/android-query-full.0.26.7.jar')
-- this is full code for json parsing with AQuery library of android
Related
how can I compress image size before uploading this is my code
I want to compress image size before its uploaded to WordPress site
I am using WordPress rest API in my android app
how can I compress image size before uploading this is my code
I want to compress image size before its uploaded to WordPress site
I am using WordPress rest API in my android app
// getting images selected from gallery for post and sending them to server
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case FilePickerConst.REQUEST_CODE_PHOTO:
if (resultCode == Activity.RESULT_OK && data != null) {
imagePaths = new ArrayList<>();
imageRequestCount = 1;
imagePaths.addAll(data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA));
if (SettingsMain.isConnectingToInternet(context)) {
if (imagePaths.size() > 0) {
btnSelectPix.setEnabled(false);
AsyncImageTask asyncImageTask = new AsyncImageTask();
asyncImageTask.execute(imagePaths);
}
}
} else {
btnSelectPix.setEnabled(true);
Toast.makeText(context, settingsMain.getAlertDialogMessage("internetMessage"), Toast.LENGTH_SHORT).show();
}
break;
}
}
private void adforest_uploadImages(List<MultipartBody.Part> parts) {
Log.d("info image parts", parts.toString());
String ad_id = Integer.toString(addId);
RequestBody adID =
RequestBody.create(
okhttp3.MultipartBody.FORM, ad_id);
Log.d("info SendImage", addId + "");
final Call<ResponseBody> req = restService.postUploadImage(adID, parts, UrlController.UploadImageAddHeaders(context));
req.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
Log.v("info Upload", response.toString());
JSONObject responseobj = null;
try {
responseobj = new JSONObject(response.body().string());
Log.d("info UploadImage object", "" + responseobj.getJSONObject("data").toString());
if (responseobj.getBoolean("success")) {
adforest_updateImages(responseobj.getJSONObject("data"));
int selectedImageSize = imagePaths.size();
int totalSize = currentSize + selectedImageSize;
Log.d("info image2", "muImage" + totalSize + "imagePaths" + totalUploadedImages);
if (totalSize == totalUploadedImages) {
adforest_UploadSuccessImage();
imagePaths.clear();
paths.clear();
if (allFile.size() > 0) {
for (File file : allFile) {
if (file.exists()) {
if (file.delete()) {
Log.d("file Deleted :", file.getPath());
} else {
Log.d("file not Deleted :", file.getPath());
}
}
}
}
}
} else {
adforest_UploadFailedImage();
Toast.makeText(context, responseobj.get("message").toString(), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
adforest_UploadFailedImage();
e.printStackTrace();
} catch (IOException e) {
adforest_UploadFailedImage();
e.printStackTrace();
}
btnSelectPix.setEnabled(true);
} else {
adforest_UploadFailedImage();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("info Upload Image Err:", t.toString());
if (t instanceof TimeoutException) {
adforest_UploadFailedImage();
// adforest_requestForImages();
}
if (t instanceof SocketTimeoutException) {
adforest_UploadFailedImage();
// adforest_requestForImages();
//
} else {
adforest_UploadFailedImage();
// adforest_requestForImages();
}
}
});
}
private void adforest_UploadFailedImage() {
progress_bar.setVisibility(View.GONE);
loadingLayout.setVisibility(View.GONE);
Gallary.setVisibility(View.VISIBLE);
Gallary.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_circle_black_24dp, 0, 0, 0);
Gallary.setText("" + 0);
Gallary.setTextColor(Color.parseColor("#a0a0a0"));
tv_done.setVisibility(View.VISIBLE);
tv_done.setTextColor(Color.parseColor("#ff0000"));
tv_done.setText(progressModel.getFailMessage());
btnSelectPix.setEnabled(true);
Toast.makeText(context, progressModel.getFailMessage(), Toast.LENGTH_SHORT).show();
}
private void adforest_UploadSuccessImage() {
progress_bar.setVisibility(View.GONE);
Gallary.setVisibility(View.VISIBLE);
loadingLayout.setVisibility(View.GONE);
Gallary.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_check_circle_green_24dp, 0, 0, 0);
Gallary.setText(totalFiles + "");
tv_done.setText(progressModel.getSuccessMessage());
Toast.makeText(context, progressModel.getSuccessMessage(), Toast.LENGTH_SHORT).show();
btnSelectPix.setEnabled(true);
tv_done.setTextColor(Color.parseColor("#20a406"));
}
private MultipartBody.Part adforestst_prepareFilePart(String fileName, Uri fileUri) {
File finalFile = new File(SettingsMain.getRealPathFromURI(context, fileUri));
allFile.add(finalFile);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(
MediaType.parse(getContentResolver().getType(fileUri)),
finalFile
);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(fileName, finalFile.getName(), requestFile);
}
private File adforest_rotateImage(String path) {
File file = null;
Bitmap bitmap = BitmapFactory.decodeFile(path);
ExifInterface ei = null;
try {
ei = new ExifInterface(path);
} catch (IOException e) {
e.printStackTrace();
}
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap rotatedBitmap = null;
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotatedBitmap = rotateImage(bitmap, 90);
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotatedBitmap = rotateImage(bitmap, 180);
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotatedBitmap = rotateImage(bitmap, 270);
break;
case ExifInterface.ORIENTATION_NORMAL:
default:
rotatedBitmap = bitmap;
}
file = new File(getRealPathFromURI(getImageUri(rotatedBitmap)));
allFile.add(file);
return file;
}
public Uri getImageUri(Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
private class AsyncImageTask extends AsyncTask<ArrayList<String>, Void, List<MultipartBody.Part>> {
ArrayList<String> imaagesLis = null;
boolean checkDimensions = true, checkImageSize;
#SafeVarargs
#Override
protected final List<MultipartBody.Part> doInBackground(ArrayList<String>... params) {
List<MultipartBody.Part> parts = null;
imaagesLis = params[0];
totalFiles = imaagesLis.size();
for (int i = 0; i < imaagesLis.size(); i++) {
parts = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
Log.d("info image", currentDateandTime);
checkDimensions = true;
checkImageSize = true;
if (adPostImageModel.getDim_is_show()) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(imaagesLis.get(i), options);
int imageWidth = options.outWidth;
int imageHeight = options.outHeight;
if (imageHeight > Integer.parseInt(adPostImageModel.getDim_height()) &&
imageWidth > Integer.parseInt(adPostImageModel.getDim_width())) {
checkDimensions = true;
} else {
checkDimensions = false;
runOnUiThread(() -> Toast.makeText(context, adPostImageModel.getDim_height_message(), Toast.LENGTH_SHORT).show());
}
}
File file = new File(imaagesLis.get(i));
long fileSizeInBytes = file.length();
Integer fileSizeBytes = Math.round(fileSizeInBytes);
if (fileSizeBytes > Integer.parseInt(adPostImageModel.getImg_size())) {
checkImageSize = false;
runOnUiThread(() -> Toast.makeText(context, adPostImageModel.getImg_message(), Toast.LENGTH_SHORT).show());
} else {
checkImageSize = true;
}
if (checkImageSize && checkDimensions) {
File finalFile1 = adforest_rotateImage(imaagesLis.get(i));
// File finalFile1 =new File(imaagesLis.get(i));
Uri tempUri = SettingsMain.decodeFile(context, finalFile1);
parts.add(adforestst_prepareFilePart("file" + i, tempUri));
adforest_uploadImages(parts);
}
}
return parts;
}
You can use this scale down function
public static Bitmap scaleDown(Bitmap your_image, float YOUR_SIZE,boolean filter) { //filter false = Pixelated, true = Smooth
float ratio = Math.min( YOUR_SIZE/ your_image.getWidth(),
YOUR_SIZE/ your_image.getHeight());
int width = Math.round( ratio * your_image.getWidth());
int height = Math.round( ratio * your_image.getHeight());
Bitmap newBitmap = Bitmap.createScaledBitmap(your_image, width, height,
filter);
return newBitmap;
}
You already have the mechanism for compressing in your code:
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
See the documentation:
https://developer.android.com/reference/android/graphics/Bitmap.html#public-methods_1
Basically you need to change 100 to a lower number in order to compress the image.
How to create URI Location to save a photo captured by a camera?
I created a intent to start camera to captured photo. I want to pass URI location through the EXTRA_OUTPUT extra. How to generate such URI.
I created PictureUtils class for capture image from camera and Gallery. Here is below code
PictureUtils.java
public class PictureUtils {
private static String fileName;
public Activity activity;
public PictureUtils(Activity activity){
this.activity = activity;
}
public Uri openCameraIntent(int requestCode) {
Uri file = null;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
file = FileProvider.getUriForFile(activity, BuildConfig.APPLICATION_ID + ".provider", getOutputMediaFile());
} else {
file = Uri.fromFile(getOutputMediaFile());
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
activity.startActivityForResult(intent, requestCode);
return file;
}
public void openGalleryIntent(int requestCode) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickPhoto.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.startActivityForResult(pickPhoto, requestCode);
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/RVRB");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
return null;
}
}
String timeStamp = String.valueOf(System.currentTimeMillis());
fileName = timeStamp + ".jpg";
return new File(mediaStorageDir.getAbsolutePath() + File.separator + fileName);
}
public ImagesData resultFromCamera(Intent data) {
File imageFile = null;
float rotationDegree = 0;
String exifOrientation;
ExifInterface exif = null;
Bitmap rotatedBitmap = null;
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/RVRB");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
imageFile = new File(storageDir, fileName);
}
try {
exif = new ExifInterface(imageFile.getAbsolutePath());
exifOrientation = exif.getAttribute(ExifInterface.TAG_ORIENTATION);
if (Integer.parseInt(exifOrientation) >= 0 && Integer.parseInt(exifOrientation) <= 1) {
rotationDegree = 0;
} else if (Integer.parseInt(exifOrientation) >= 2 && Integer.parseInt(exifOrientation) <= 4) {
rotationDegree = 180;
} else if (Integer.parseInt(exifOrientation) >= 7 && Integer.parseInt(exifOrientation) >= 8) {
rotationDegree = 270;
} else {
rotationDegree = 90;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
Bitmap thumbnail = null;
if (data != null && data.getData() != null) {
try {
thumbnail = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), data.getData());
Matrix matrix = new Matrix();
matrix.postRotate(rotationDegree);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(thumbnail, thumbnail.getWidth(), thumbnail.getHeight(), true);
rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
if (imageFile != null) {
OutputStream fOut = new FileOutputStream(imageFile);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
fOut.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
thumbnail = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), Uri.fromFile(imageFile));
Matrix matrix = new Matrix();
matrix.postRotate(rotationDegree);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(thumbnail, thumbnail.getWidth(), thumbnail.getHeight(), true);
rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
if (imageFile != null) {
OutputStream fOut = new FileOutputStream(imageFile);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
fOut.close();
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
try {
Bitmap bitmap = null;
imageFile = new File(storageDir, fileName);
bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), Uri.fromFile(imageFile));
if (bitmap != null && (bitmap.getHeight() < bitmap.getWidth())) {
Matrix matrix = new Matrix();
matrix.postRotate(rotationDegree);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
if (imageFile != null) {
OutputStream fOut = new FileOutputStream(imageFile);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
fOut.close();
}
} else {
rotatedBitmap = bitmap;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return new ImagesData(imageFile, rotatedBitmap);
}
public ImagesData imageFromGallery(Intent data) {
File imageFile = null;
float rotationDegree = 0;
Bitmap rotatedBitmap = null;
try {
Bitmap bm = null;
Uri selectedImage = null;
if (data != null && data.getData() != null) {
try {
selectedImage = data.getData();
bm = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), selectedImage);
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
bm = (Bitmap) data.getExtras().get("data");
} catch (Exception e) {
e.printStackTrace();
}
}
String timeStamp = String.valueOf(System.currentTimeMillis());
String fileName = timeStamp + ".jpg";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/RVRB");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
imageFile = new File(storageDir, fileName);
}
rotationDegree = getRotationFromURI(selectedImage, activity);
Matrix matrix = new Matrix();
matrix.postRotate(rotationDegree);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(bm, bm.getWidth(), bm.getHeight(), true);
rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
if (imageFile != null) {
OutputStream fOut = new FileOutputStream(imageFile);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 70, fOut);
fOut.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return new ImagesData(imageFile, rotatedBitmap);
}
private int getRotationFromURI(Uri contentUri, Context mContext) {
Cursor cursor = null;
try {
String[] proj = new String[]{MediaStore.Images.ImageColumns.ORIENTATION};
cursor = mContext.getContentResolver().query(contentUri, proj, null, null, null);
assert cursor != null;
cursor.moveToFirst();
return cursor.getInt(0);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
return 0;
}
public class ImagesData {
File imageFile = null;
Bitmap bitmap = null;
private ImagesData(File imageFile, Bitmap bitmap) {
this.imageFile = imageFile;
this.bitmap = bitmap;
}
public File getImageFile() {
return imageFile;
}
public void setImageFile(File imageFile) {
this.imageFile = imageFile;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
}
}
Now you can call camera intent using below way on click of any button.
Global Declaration : Uri fileUri;
PictureUtils images = new PictureUtils(ArtistAddEditMembers.this);
fileUri = images.openCameraIntent(REQUEST_OPEN_CAMERA);
You can handel the result in onActivityResult method using below way.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_OPEN_CAMERA) {
try {
PictureUtils images = new PictureUtils(ArtistAddEditMembers.this);
PictureUtils.ImagesData imagesData = images.resultFromCamera(data);
imageFile = imagesData.getImageFile();
finalBitmap = imagesData.getBitmap();
displayImagePreview(finalBitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == REQUEST_OPEN_GALLERY) {
try {
PictureUtils images = new PictureUtils(ArtistAddEditMembers.this);
PictureUtils.ImagesData imagesData = images.imageFromGallery(data);
imageFile = imagesData.getImageFile();
finalBitmap = imagesData.getBitmap();
displayImagePreview(finalBitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
For Display image in imageview
public void displayImagePreview(Bitmap bitmap) {
Glide.with(mContext).load(bitmap).into(ivUserProfile);
}
or you can simply set image bitmap in imageview without using glide.
I handeled below case in above example.
If version is >= N, the I am using FileProvider.getUriForFile and Uri.fromFile for lower version.
Display right rotation of Image instead of Display image after rotate.
Add below code in AndroidManefest.xml file under application tag for file provider
<application
......>
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/filepaths" />
</provider>
</application>
Create filepaths.xml file under xml resource directory
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
Make sure you popup and handel runtime permission for Camera and Write Internal Storage permission before call camera intent.
Use this code for generate and call that file into camera intent
File imagefile = null;
try {
imagefile = createImageFile();
} catch (IOException ex) {
// Error while creating the File
Log.i(TAG, "IOException");
}
if (imagefile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
here is code of generate Imagefile
private File createImageFile() throws IOException {
String imageFileName = "JPEG_" + System.currentTimeMillis() + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
return image;
}
private void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
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();
}
}
Im taking a photo with the following code
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoPath = new File(getExternalFilesDir(null), "postcard.jpg");
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoPath));
log.debug("start camera for {}", photoPath.getAbsolutePath());
startActivityForResult(takePhotoIntent, REQUEST_TAKE_PHOTO);
...
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO) {
if (resultCode == RESULT_OK) {
log.debug("photo successfully created");
} else {
log.error("problem to take photo resultCode={}", resultCode);
}
} else {
log.debug("not my request: {}", requestCode);
}
}
This works fine on Android 5, but fails on Android 6 with resultCode=0 (RESULT_CANCELED) and the logcat error message:
03-09 07:56:13.759 878-3735/? W/ActivityManager: Appop Denial:
starting Intent { act=android.media.action.IMAGE_CAPTURE flg=0x3
cmp=com.google.android.GoogleCamera/com.android.camera.CaptureActivity
clip={text/uri-list
U:file:///storage/emulated/0/Android/data/censored.package.name.here/files/postcard.jpg}
(has extras) } from ProcessRecord{55cce35
21309:censored.package.name.here/u0a136} (pid=21309, uid=10136)
requires android:camera
I have the following in the Android Manifest:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
I also check if the application really has the camera permission, this check passes.
checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
Also worth noting, I include an aar in the project that also uses the camera. This included library has this in the manifest:
<uses-feature android:name="android.hardware.camera" android:required="false"/>
<uses-feature android:name="android.hardware.camera.front" android:required="false"/>
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false"/>
<uses-feature android:name="android.hardware.camera.flash" android:required="false"/>
<uses-feature android:name="android.hardware.screen.landscape" android:required="false" />
<uses-feature android:name="android.hardware.wifi" android:required="false"/>
Does anybody have an idea what the error message means or how to fix this? Google wasn't helpful in this case.
Up to now, I wasn't successful to reproduce the problem with a small example. It seems to be some interaction with another app part.
After more than a day experimenting and debugging it works now. The code is still exactly the same.
I guess, retracting the camera permission via the settings and then re-enabling it did the trick but I am not completely sure.
Posting this as an answer if somebody runs into the same problem.
-- Complete code for capturing image ,saving to SD card , pick from gallery,compress,rotate image,etc.. 200% working.
public class A extends AppCompatActivity implements View.OnClickListener, AsyncTaskCompleteListener {
private static final String IMAGE_DIRECTORY = "/idyme";
private static int MAX_IMAGE_DIMENSION = 200;
private final String TAG = "RegisterFragment";
private Button btnVerify, btnUploadImage;
private String ImgPath = null, filePath = null,
profileImageFilePath, profileImageData = null,imageVideoType = "", imageVideoPath = "";
private ImageView ivImage;
private AQuery aQuery;
private Uri uri = null;
private ImageOptions imageOptions;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vip_registration);
ivImage = (ImageView) findViewById(R.id.ivProfile);
aQuery = new AQuery(this);
imageOptions = new ImageOptions();
imageOptions.memCache = true;
imageOptions.fileCache = true;
imageOptions.fallback = R.drawable.userimage;
}
#Override
public void onClick(View v) {
// onRegisterButtonClick();
switch (v.getId()) {
case R.id.btnUploadImage:
showPictureDialog();
}
}
private void showPictureDialog() {
AlertDialog.Builder pictureDialog = new AlertDialog.Builder(this);
pictureDialog.setTitle(getResources().getString(
R.string.dialog_chhose_photo));
String[] pictureDialogItems = {
getResources().getString(R.string.dialog_from_gallery),
getResources().getString(R.string.dialog_from_camera)};
pictureDialog.setItems(pictureDialogItems,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
choosePhotoFromGallary();
break;
case 1:
takePhotoFromCamera();
break;
}
}
});
pictureDialog.show();
}
private void choosePhotoFromGallary() {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, Constants.CHOOSE_PHOTO);
}
private void takePhotoFromCamera() {
Calendar cal = Calendar.getInstance();
File file = new File(Environment.getExternalStorageDirectory(),
(cal.getTimeInMillis() + ".jpg"));
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
} else {
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
// uri = Uri.fromFile(file);
uri = getOutputMediaFileUri();
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cameraIntent, Constants.TAKE_PHOTO);
}
public Uri getOutputMediaFileUri() {
return Uri.fromFile(getOutputMediaFile());
}
private String getRealPathFromURI(Uri contentURI) {
String result;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = this.getContentResolver().query(contentURI, proj, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file
// path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == Constants.CHOOSE_PHOTO) {
if (data != null) {
Uri contentURI = data.getData();
profileImageData = getRealPathFromURI(contentURI);
// new AQuery(getApplicationContext()).id(ivMeme).image(
// profileImageData, imageOptions);
try {
String path = saveImage(scaleImage(this, contentURI));
imageVideoPath = path;
aQuery.id(R.id.ivProfile).image(
imageVideoPath, imageOptions);
} catch (IOException e) {
e.printStackTrace();
Utils.showToast("Failed", this);
}
}
} else if (requestCode == Constants.TAKE_PHOTO) {
// old
if (uri != null) {
profileImageFilePath = uri.getPath();
if (profileImageFilePath != null
&& profileImageFilePath.length() > 0) {
File myFile = new File(profileImageFilePath);
String path = saveImage(BitmapFactory
.decodeFile(profileImageFilePath));
imageVideoPath = path;
aQuery.id(R.id.ivProfile).image(
imageVideoPath, imageOptions);
} else {
Utils.showToast("Failed", this);
}
} else {
Utils.showToast("Failed", this);
}
}
}
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File wallpaperDirectory = new File(
Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY);
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
File f = new File(wallpaperDirectory, Calendar.getInstance()
.getTimeInMillis() + ".jpg");
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
MediaScannerConnection.scanFile(this,
new String[]{f.getPath()},
new String[]{"image/jpeg"}, null);
fo.close();
AppLog.Log("TAG", "File Saved::-> " + f.getAbsolutePath());
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
private static File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY, "Oops! Failed create " + IMAGE_DIRECTORY
+ " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
return mediaFile;
}
public static Bitmap scaleImage(Context context, Uri photoUri)
throws IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = getOrientation(context, photoUri);
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
if (rotatedWidth > MAX_IMAGE_DIMENSION
|| rotatedHeight > MAX_IMAGE_DIMENSION) {
float widthRatio = ((float) rotatedWidth)
/ ((float) MAX_IMAGE_DIMENSION);
float heightRatio = ((float) rotatedHeight)
/ ((float) MAX_IMAGE_DIMENSION);
float maxRatio = Math.max(widthRatio, heightRatio);
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
srcBitmap = BitmapFactory.decodeStream(is, null, options);
} else {
srcBitmap = BitmapFactory.decodeStream(is);
}
is.close();
/*
* if the orientation is not 0 (or -1, which means we don't know), we
* have to do a rotation.
*/
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0,
srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);
}
String type = context.getContentResolver().getType(photoUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (type.equals("image/png")) {
srcBitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
} else if (type.equals("image/jpg") || type.equals("image/jpeg")) {
srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
}
byte[] bMapArray = baos.toByteArray();
baos.close();
return BitmapFactory.decodeByteArray(bMapArray, 0, bMapArray.length);
}
public static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[]{MediaStore.Images.ImageColumns.ORIENTATION},
null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
}
-- Permission required :
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
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