Android Opening Front Camera by default - android

I am very new to android and for some reason I have to implement a code that would let open the front camera by default instead of rear camera. My minimum SDK is API 9 and Target SDK is API 21. I have a PicturePlugin.Java file and the code is:
public class PicturePlugin extends CordovaPlugin
{
private String callback="data";
private int IMAGE_TAKEN=1;
private CallbackContext callbackContext;
private String TAG="FilePlugin";
private int imageWidth,imageHeight;
private String imagePath;
private File destImageFile;
private String mode = "BACK";
private static String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
CameraManager manager;
private static final String TAG1 = null ;
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
{
this.callbackContext = callbackContext;
this.cordova.getActivity().getApplicationContext().getPackageName();
try
{
JSONObject object=(JSONObject) args.get(0);
imageWidth=object.getInt("targetWidth");
imageHeight=object.getInt("targetHeight");
if(object.has("mode")){
if(object.getString("mode").equals("FRONT")){
mode = "FRONT";
openFrontFacingCamera();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("android.intent.extras.CAMERA_FACING", android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
}
}else{
mode = "BACK";
}
Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imagePath = getCapturedImageExternal();
destImageFile = new File(imagePath);
camera.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(destImageFile));
this.cordova.setActivityResultCallback(PicturePlugin.this);
cordova.getActivity().startActivityForResult(camera,IMAGE_TAKEN);
}
catch (Exception e)
{
Log.i(TAG, "Exception "+e.getMessage());
callbackContext.error("failed");
}
return true;
}
private Camera openFrontFacingCamera()
{
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for ( int camId = 0; camId < cameraCount; camId++ ) {
Camera.getCameraInfo( camId, cameraInfo );
if ( cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT ) {
try {
cam = Camera.open( camId );
} catch (RuntimeException e) {
Log.e(TAG1, "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == IMAGE_TAKEN && resultCode == Activity.RESULT_OK) {
File finalFile = null;
File fileTobeDeleted = null;
Bitmap photo = null;
File sd = new File(Environment.getExternalStorageDirectory(),
Constants.GOBIZMO_IMAGE_DIR);
String destinationImagePath = File.separator
+ Constants.TEMP_CAMERA_IMAGE + ".JPEG";
File destination = new File(sd, destinationImagePath);
sd.setWritable(true);
try {
String encoded;
imagePath = destImageFile.getAbsolutePath();
finalFile = new File(imagePath);
fileTobeDeleted = new File(imagePath);
int angle = getAngle(finalFile.getAbsolutePath());
if (finalFile.exists()) {
photo = BitmapFactory.decodeFile(finalFile
.getAbsolutePath());
Matrix matrix = new Matrix();
matrix.postRotate(angle);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(photo, imageWidth, imageHeight, true);
photo = Bitmap.createBitmap(scaledBitmap, 0, 0, imageWidth, imageHeight, matrix, true);
// //////New orientation fix for all
// devices///////////////////////
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
Log.e("base 64 image", encoded);
JSONObject object = new JSONObject();
object.put(callback, encoded);
finalFile.delete();
fileTobeDeleted.delete();
//imagePath = destination.getPath();
if(new File(imagePath).exists()){
new File(imagePath).delete();
}
callbackContext.success(encoded);
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "onActivityResult " + e.getMessage());
finalFile.delete();
fileTobeDeleted.delete();
if(new File(imagePath).exists()){
new File(imagePath).delete();
}
callbackContext.error("failed");
}
}
} catch (Exception exp) {
exp.printStackTrace();
Log.i(TAG, "onActivityResult " + exp.getMessage());
try {
finalFile.delete();
fileTobeDeleted.delete();
imagePath = destination.getPath();
if(new File(imagePath).exists()){
new File(imagePath).delete();
}
callbackContext.error("failed");
}catch(Exception innerexception){
innerexception.printStackTrace();
}
}
}
}
public Uri getImageUri(Context inContext, Bitmap inImage)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri)
{
Cursor cursor = cordova.getActivity().getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(Images.ImageColumns.DATA);
return cursor.getString(idx);
}
public static String getCapturedImageExternal() {
// External sdcard location
File mediaStorageDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"Gobizmo image");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()){
mediaStorageDir.mkdirs();
}
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) {
Log.d(Constants.GOBIZMO_IMAGE_DIR, "Oops! Failed create "
+ Constants.GOBIZMO_IMAGE_DIR + " directory");
return null;
}
// Create a timestamp
return mediaStorageDir.getPath() + File.separator + Constants.TEMP_CAMERA_IMAGE
+ ".JPEG";
}
public static String getRealPathFromURI(Context context, Uri contentUri) {
String filepath = "";
String uriPath = contentUri.toString();
// Handle local file and remove url encoding
if (uriPath.startsWith("file://")) {
filepath = uriPath.replace("file://", "");
try {
return URLDecoder.decode(filepath, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
try {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri,
projection, null, null, null);
if (cursor != null && cursor.getCount() != 0) {
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
filepath = cursor.getString(column_index);
}
} catch (Exception e) {
Log.e("Path Error", e.toString());
}
return filepath;
}
private int getAngle(String path)
{
int angle=0;
try
{
ExifInterface ei = new ExifInterface(path);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
Log.i(TAG, "getAngle "+orientation);
switch(orientation)
{
case ExifInterface.ORIENTATION_ROTATE_90:
angle=90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
angle=180;
break;
case ExifInterface.ORIENTATION_ROTATE_270 :
angle=270;
default:
angle=0;
}
}
catch(Exception ex)
{
Log.i("getAngle", "getAngle :: "+ex.getMessage());
}
return angle;
}
}
Please help me. This is my first plugin handling.

This code will work whenever the JSON object 'mode' will be found:
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONObject;
import org.maxmobility.util.Constants;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.camera2.CameraManager;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.util.Log;
import android.view.SurfaceHolder;
public class PicturePlugin extends CordovaPlugin
{
private String callback="data";
private int IMAGE_TAKEN=1;
private CallbackContext callbackContext;
private String TAG="FilePlugin";
private int imageWidth,imageHeight;
private String imagePath;
private File destImageFile;
private String mode = "BACK";
private static String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
static Camera camera = null;
private static final String TAG1 = null ;
public boolean execute(String action, JSONArray args, CallbackContext callbackContext)
{
this.callbackContext = callbackContext;
this.cordova.getActivity().getApplicationContext().getPackageName();
try
{
JSONObject object=(JSONObject) args.get(0);
imageWidth=object.getInt("targetWidth");
imageHeight=object.getInt("targetHeight");
//checking whether json object has "mode" or not
if(object.has("mode"))
{
//if json object has "mode" and that is "FRONT"
if(object.getString("mode").equals("FRONT"))
{
mode = "FRONT";
Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra("android.intent.extras.CAMERA_FACING", 1); // used this line of code to start the intent of camera
//The ID is 1 that opens FRONT CAMERA of a device
imagePath = getCapturedImageExternal();
destImageFile = new File(imagePath);
camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destImageFile));
this.cordova.setActivityResultCallback(PicturePlugin.this);
cordova.getActivity().startActivityForResult(camera,IMAGE_TAKEN);
}
else
{
// if json object has "mode" and that is "BACK"
mode = "BACK";
Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra("android.intent.extras.CAMERA_FACING", 0); //ID is 0 that opens REAR CAMERA of a device
imagePath = getCapturedImageExternal();
destImageFile = new File(imagePath);
camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destImageFile));
this.cordova.setActivityResultCallback(PicturePlugin.this);
cordova.getActivity().startActivityForResult(camera,IMAGE_TAKEN);
}
}
else
{
//if no "mode" is found in json object then by default rear camera is opening
Intent camera=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera.putExtra("android.intent.extras.CAMERA_FACING", 0);
imagePath = getCapturedImageExternal();
destImageFile = new File(imagePath);
camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destImageFile));
this.cordova.setActivityResultCallback(PicturePlugin.this);
cordova.getActivity().startActivityForResult(camera,IMAGE_TAKEN);
}
}
catch (Exception e)
{
Log.i(TAG, "Exception "+e.getMessage());
callbackContext.error("failed");
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
if (requestCode == IMAGE_TAKEN && resultCode == Activity.RESULT_OK) {
File finalFile = null;
File fileTobeDeleted = null;
Bitmap photo = null;
File sd = new File(Environment.getExternalStorageDirectory(),
Constants.GOBIZMO_IMAGE_DIR);
String destinationImagePath = File.separator
+ Constants.TEMP_CAMERA_IMAGE + ".JPEG";
File destination = new File(sd, destinationImagePath);
sd.setWritable(true);
try {
String encoded;
imagePath = destImageFile.getAbsolutePath();
finalFile = new File(imagePath);
fileTobeDeleted = new File(imagePath);
int angle = getAngle(finalFile.getAbsolutePath());
if (finalFile.exists()) {
photo = BitmapFactory.decodeFile(finalFile
.getAbsolutePath());
Matrix matrix = new Matrix();
matrix.postRotate(angle);
Bitmap scaledBitmap = Bitmap.createScaledBitmap(photo, imageWidth, imageHeight, true);
photo = Bitmap.createBitmap(scaledBitmap, 0, 0, imageWidth, imageHeight, matrix, true);
// //////New orientation fix for all
// devices///////////////////////
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
Log.e("base 64 image", encoded);
JSONObject object = new JSONObject();
object.put(callback, encoded);
finalFile.delete();
fileTobeDeleted.delete();
//imagePath = destination.getPath();
if(new File(imagePath).exists()){
new File(imagePath).delete();
}
callbackContext.success(encoded);
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "onActivityResult " + e.getMessage());
finalFile.delete();
fileTobeDeleted.delete();
if(new File(imagePath).exists()){
new File(imagePath).delete();
}
callbackContext.error("failed");
}
}
} catch (Exception exp) {
exp.printStackTrace();
Log.i(TAG, "onActivityResult " + exp.getMessage());
try {
finalFile.delete();
fileTobeDeleted.delete();
imagePath = destination.getPath();
if(new File(imagePath).exists()){
new File(imagePath).delete();
}
callbackContext.error("failed");
}catch(Exception innerexception){
innerexception.printStackTrace();
}
}
}
}
public Uri getImageUri(Context inContext, Bitmap inImage)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri)
{
Cursor cursor = cordova.getActivity().getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(Images.ImageColumns.DATA);
return cursor.getString(idx);
}
public static String getCapturedImageExternal() {
// External sdcard location
File mediaStorageDir = new File(
android.os.Environment.getExternalStorageDirectory(),
"Gobizmo image");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()){
mediaStorageDir.mkdirs();
}
if (!mediaStorageDir.exists() && !mediaStorageDir.mkdirs()) {
Log.d(Constants.GOBIZMO_IMAGE_DIR, "Oops! Failed create "
+ Constants.GOBIZMO_IMAGE_DIR + " directory");
return null;
}
// Create a timestamp
return mediaStorageDir.getPath() + File.separator + Constants.TEMP_CAMERA_IMAGE
+ ".JPEG";
}
public static String getRealPathFromURI(Context context, Uri contentUri) {
String filepath = "";
String uriPath = contentUri.toString();
// Handle local file and remove url encoding
if (uriPath.startsWith("file://")) {
filepath = uriPath.replace("file://", "");
try {
return URLDecoder.decode(filepath, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
try {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri,
projection, null, null, null);
if (cursor != null && cursor.getCount() != 0) {
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
filepath = cursor.getString(column_index);
}
} catch (Exception e) {
Log.e("Path Error", e.toString());
}
return filepath;
}
private int getAngle(String path)
{
int angle=0;
try
{
ExifInterface ei = new ExifInterface(path);
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
Log.i(TAG, "getAngle "+orientation);
switch(orientation)
{
case ExifInterface.ORIENTATION_ROTATE_90:
angle=90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
angle=180;
break;
case ExifInterface.ORIENTATION_ROTATE_270 :
angle=270;
default:
angle=0;
}
}
catch(Exception ex)
{
Log.i("getAngle", "getAngle :: "+ex.getMessage());
}
return angle;
}
}
Do not forget to add permission to use front camera in your manifest.xml.
it will be:
<uses-feature android:name="android.hardware.camera.front" /> <!-- used this feature to open the front camera -->

This Code Help you
private Camera openFrontFacingCameraGingerbread() {
int cameraCount = 0;
Camera cam = null;
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
cameraCount = Camera.getNumberOfCameras();
for (int camIdx = 0; camIdx<cameraCount; camIdx++) {
Camera.getCameraInfo(camIdx, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
try {
cam = Camera.open(camIdx);
} catch (RuntimeException e) {
Log.e("Your_TAG", "Camera failed to open: " + e.getLocalizedMessage());
}
}
}
return cam;
}
With add this permission in your app
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />

This might help.
For the full code https://github.com/googlesamples/android-Camera2Basic
Get the front or back lens by:
Activity activity = getActivity();
CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
try {
for (String cameraId : manager.getCameraIdList()) {
CameraCharacteristics characteristics
= manager.getCameraCharacteristics(cameraId);
// Choose front or back lens
Integer facing = characteristics.get(CameraCharacteristics.LENS_FACING);
if (facing != null && facing == CameraCharacteristics.LENS_FACING_BACK) {
continue;
}

We can not see the json object you are parsing, if this condition is met,
object.getString("mode").equals("FRONT")
then your code is looking for the cameras and opening the front one...

Related

camera intent data null in onActivityResult(int requestCode, int resultCode, Intent data) in Samsung S4

I am getting camera intent's data null in onActivityResult(int requestCode, int resultCode, Intent data) in Samsung S4. But working well on some other devices. I customized my code for getting data and searched this issue in web but nothing found useful.please help me some one
my code:-
/**
* chooseImageFromCamera
*/
private void chooseImageFromCamera() {
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, Constants.CAMERA_REQUEST_CODE);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
/**
* onCaptureImageResult
*
* #param
*/
private void onCaptureImageResult(Intent data) {
try {
if (data.getData() != null) {
Uri contentUri = data.getData();
String selectedFilePath = ImageFilePath.getPath(
this, contentUri);
File file = new File(selectedFilePath);
} else {
if (data.getExtras().get("data") != null) {
System.out.println("else block");
Bitmap photo = (Bitmap) data.getExtras().get("data");
Uri contentUri = Utilities.getImageUri(this, photo);
String selectedFilePath = ImageFilePath.getPath(
this, contentUri);
File file = new File(selectedFilePath);
}
}
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
try this One.
ImagePicker.java put in your app
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import static android.R.attr.orientation;
import static android.view.OrientationEventListener.ORIENTATION_UNKNOWN;
/**
* Created by creativeinfoway2 on 06/11/16.
*/
public class ImagePicker {
private static final int DEFAULT_MIN_WIDTH_QUALITY = 400; // min pixels
private static final String TAG = "ImagePicker";
private static final String TEMP_IMAGE_NAME = "tempImage";
public static int minWidthQuality = DEFAULT_MIN_WIDTH_QUALITY;
public static Intent getPickImageIntent(Context context) {
Intent chooserIntent = null;
List<Intent> intentList = new ArrayList<>();
Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra("return-data", true);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
intentList = addIntentsToList(context, intentList, pickIntent);
intentList = addIntentsToList(context, intentList, takePhotoIntent);
if (intentList.size() > 0) {
chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1),
context.getString(R.string.pick_image));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
}
return chooserIntent;
}
private static List<Intent> addIntentsToList(Context context, List<Intent> list, Intent intent) {
List<ResolveInfo> resInfo = context.getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo resolveInfo : resInfo) {
String packageName = resolveInfo.activityInfo.packageName;
Intent targetedIntent = new Intent(intent);
targetedIntent.setPackage(packageName);
list.add(targetedIntent);
Log.d(TAG, "Intent: " + intent.getAction() + " package: " + packageName);
}
return list;
}
public static Bitmap getImageFromResult(Context context, int resultCode,
Intent imageReturnedIntent) {
Log.d(TAG, "getImageFromResult, resultCode: " + resultCode);
Bitmap bm = null;
File imageFile = getTempFile(context);
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage;
boolean isCamera = (imageReturnedIntent == null ||
imageReturnedIntent.getData() == null ||
imageReturnedIntent.getData().toString().contains(imageFile.toString()));
if (isCamera) {
/** CAMERA **/
selectedImage = Uri.fromFile(imageFile);
} else { /** ALBUM **/
selectedImage = imageReturnedIntent.getData();
}
Log.d(TAG, "selectedImage: " + selectedImage);
bm = getImageResized(context, selectedImage);
int rotation = getRotation(context, selectedImage, isCamera);
bm = rotate(bm, rotation);
}
return bm;
}
private static File getTempFile(Context context) {
File imageFile = new File(context.getExternalCacheDir(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
private static Bitmap decodeBitmap(Context context, Uri theUri, int sampleSize) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = sampleSize;
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(theUri, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(
fileDescriptor.getFileDescriptor(), null, options);
Log.d(TAG, options.inSampleSize + " sample method bitmap ... " +
actuallyUsableBitmap.getWidth() + " " + actuallyUsableBitmap.getHeight());
return actuallyUsableBitmap;
}
/**
* Resize to avoid using too much memory loading big images (e.g.: 2560*1920)
**/
private static Bitmap getImageResized(Context context, Uri selectedImage) {
Bitmap bm = null;
int[] sampleSizes = new int[]{5, 3, 2, 1};
int i = 0;
do {
bm = decodeBitmap(context, selectedImage, sampleSizes[i]);
Log.d(TAG, "resizer: new bitmap width = " + bm.getWidth());
i++;
} while (bm.getWidth() < minWidthQuality && i < sampleSizes.length);
return bm;
}
private static int getRotation(Context context, Uri imageUri, boolean isCamera) {
int rotation;
if (isCamera) {
rotation = getRotationFromCamera(context, imageUri);
} else {
rotation = getRotationFromGallery(context, imageUri);
}
Log.d(TAG, "Image rotation: " + rotation);
return rotation;
}
private static int getRotationFromCamera(Context context, Uri imageFile) {
int rotate = 0;
try {
context.getContentResolver().notifyChange(imageFile, null);
ExifInterface exif = new ExifInterface(imageFile.getPath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
} catch (Exception e) {
e.printStackTrace();
}
return rotate;
}
public static int getRotationFromGallery(Context context, Uri imageUri) {
int result = 0;
String[] columns = {MediaStore.Images.Media.ORIENTATION};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(imageUri, columns, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int orientationColumnIndex = cursor.getColumnIndex(columns[0]);
result = cursor.getInt(orientationColumnIndex);
}
} catch (Exception e) {
//Do nothing
} finally {
if (cursor != null) {
cursor.close();
}
}//End of try-catch block
return result;
}
private static Bitmap rotate(Bitmap bm, int rotation) {
if (rotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
Bitmap bmOut = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
return bmOut;
}
return bm;
}
}
After that when clicking on button or image OnClickListner use this
img_upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent chooseImageIntent = ImagePicker.getPickImageIntent(getActivity());
startActivityForResult(chooseImageIntent, 101);
// openGallery();
}
});
After in OnActivityResult
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case 101:
Bitmap bitmap = ImagePicker.getImageFromResult(getActivity(),resultCode,data);
img_upload.setImageBitmap(bitmap);
break;
}
}
Hope it helps.

Json parsing with AQuery library of android

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

Error saving video Uri to SD card

I am trying to save a video from VideoView to the SD card, by touching the VideoView. No errors in LogCat, but my Toast I set up says "Error during video saving", which tells me my boolean I set up did not get to the part where it's set to true. It must be in the file I/O part. One part that works though, is a directory does get created, but the file itself is not found in the directory, it's empty.
Any mistakes anyone sees?
I will post my two main methods that are important, then below I'll post the whole class.
UPDATE: Here is my working code (changed a couple lines in the saveVideo method.)
// save your video to SD card
protected void saveVideo(final Uri uriVideo){
// click the video to save it
mVideoView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
boolean success = false;
// make the directory
File vidDir = new File(android.os.Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_MOVIES) + File.separator + "Saved iCute Videos");
vidDir.mkdirs();
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
File fileVideo = new File(vidDir.getAbsolutePath(), videoName);
try {
fileVideo.createNewFile();
success = true;
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
return true;
}
});
}
My old, unworking saveVideo() method.
// save your video to SD card
protected void saveVideo(final Uri uriVideo){
// click the video to save it
mVideoView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
String sourceVideoName = uriVideo.getPath();
boolean success = false;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
// make the directory
File vidDir = new File(android.os.Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_MOVIES) + File.separator + "Saved iCute Videos");
vidDir.mkdirs();
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
fileVideo = new File(vidDir.getPath(), videoName);
try {
bis = new BufferedInputStream(new FileInputStream(sourceVideoName));
bos = new BufferedOutputStream(new FileOutputStream(fileVideo, false));
byte[] buf = new byte[8192];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != 0);
success = true;
} catch (IOException e) {
}finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
}
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
return true;
}
});
}
My dispatchTakeVideoIntent() method. I commented out some code that might be needed... I kept getting a null pointer though on fileUri line (was it from fileUri or fileVideo?), so not sure why.
// Captures video from Android camera component
protected void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
// // set name of video
// Uri fileUri = Uri.fromFile(fileVideo);
// takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// set the video image quality to high
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
}
}
MakePhotoVideo.java
package org.azurespot.makecute;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;
import org.azurespot.R;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
public class MakePhotoVideo extends ActionBarActivity {
private static final int ACTION_TAKE_PHOTO = 1;
private static final int ACTION_TAKE_VIDEO = 2;
private static final String BITMAP_STORAGE_KEY = "viewbitmap";
private static final String IMAGEVIEW_VISIBILITY_STORAGE_KEY = "imageviewvisibility";
private ImageView mImageView;
private Bitmap mImageBitmap;
private static final String VIDEO_STORAGE_KEY = "viewvideo";
private static final String VIDEOVIEW_VISIBILITY_STORAGE_KEY = "videoviewvisibility";
private VideoView mVideoView;
private Uri mVideoUri;
File fileVideo;
private String mCurrentPhotoPath;
private static final String JPEG_FILE_PREFIX = "IMG_";
private static final String JPEG_FILE_SUFFIX = ".jpg";
private PhotoStorageDirFactory mPhotoStorageDirFactory = null;
/* Photo album for this application */
private String getAlbumName() {
return getString(R.string.album_name);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_photo_video);
mImageView = (ImageView) findViewById(R.id.taken_photo);
mVideoView = (VideoView) findViewById(R.id.video_view);
mVideoView.setVisibility(View.INVISIBLE);
mImageBitmap = null;
mVideoUri = null;
Button photoBtn = (Button) findViewById(R.id.click);
setBtnListenerOrDisable(
photoBtn,
mTakePicOnClickListener,
MediaStore.ACTION_IMAGE_CAPTURE
);
Button videoBtn = (Button) findViewById(R.id.record_video);
setBtnListenerOrDisable(
videoBtn,
mTakeVidOnClickListener,
MediaStore.ACTION_VIDEO_CAPTURE
);
mPhotoStorageDirFactory = new BasePhotoDirFactory();
// Shows the up carat near app icon in ActionBar
getSupportActionBar().setDisplayUseLogoEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = mPhotoStorageDirFactory.getAlbumStorageDir(getAlbumName());
if (storageDir != null) {
if (! storageDir.mkdirs()) {
if (! storageDir.exists()){
Log.d("Camera", "failed to create directory");
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, albumF);
return imageF;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
private void setPic() {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* Decode the JPEG file into a Bitmap */
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
bitmap = rotateBitmap(bitmap, 90);
savePhoto(bitmap);
/* Associate the Bitmap to the ImageView, make sure the VideoView
* is cleared to replace with ImageView */
mImageView.setImageBitmap(bitmap);
mVideoUri = null;
mImageView.setVisibility(View.VISIBLE);
mVideoView.setVisibility(View.INVISIBLE);
}
// save your photo to SD card
private void savePhoto(final Bitmap bitmapPhoto){
// set OnClickListener to save the photo
mImageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
boolean success = false;
File photoDir = new File(Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_PICTURES) + "/Saved iCute Photos");
photoDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String photoName = "Image_"+ n +".jpg";
File filePhoto = new File (photoDir, photoName);
// if (filePhoto.exists ()) filePhoto.delete ();
try {
FileOutputStream out = new FileOutputStream(filePhoto);
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
success = true;
} catch (Exception e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Image saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
}
});
}
// save your video to SD card
protected void saveVideo(final Uri uriVideo){
// click the video to save it
mVideoView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
String sourceVideoName = uriVideo.getPath();
boolean success = false;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
// make the directory
File vidDir = new File(android.os.Environment.getExternalStoragePublicDirectory
(Environment.DIRECTORY_MOVIES) + File.separator + "Saved iCute Videos");
vidDir.mkdirs();
// create unique identifier
Random generator = new Random();
int n = 100;
n = generator.nextInt(n);
// create file name
String videoName = "Video_" + n + ".mp4";
fileVideo = new File(vidDir.getPath(), videoName);
try {
bis = new BufferedInputStream(new FileInputStream(sourceVideoName));
bos = new BufferedOutputStream(new FileOutputStream(fileVideo, false));
byte[] buf = new byte[8192];
bis.read(buf);
do {
bos.write(buf);
} while (bis.read(buf) != 0);
success = true;
} catch (IOException e) {
}finally {
try {
if (bis != null) bis.close();
if (bos != null) bos.close();
} catch (IOException e) {
}
}
if (success) {
Toast.makeText(getApplicationContext(), "Video saved!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during video saving", Toast.LENGTH_LONG).show();
}
return true;
}
});
}
public Bitmap rotateBitmap(Bitmap source, int angle)
{
Matrix matrix = new Matrix();
matrix.set(matrix);
matrix.setRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(),
source.getHeight(), matrix, false);
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch(actionCode) {
case ACTION_TAKE_PHOTO:
File f;
try {
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
} // switch
startActivityForResult(takePictureIntent, actionCode);
}
// Captures video from Android camera component
protected void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
// // set name of video
// Uri fileUri = Uri.fromFile(fileVideo);
// takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// set the video image quality to high
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(takeVideoIntent, ACTION_TAKE_VIDEO);
}
}
private void handleCameraPhoto() {
if (mCurrentPhotoPath != null) {
setPic();
galleryAddPic();
mCurrentPhotoPath = null;
}
}
// Post recorded video into VideoView
private void handleCameraVideo(Intent intent) {
mVideoUri = intent.getData();
mVideoView.setVideoURI(mVideoUri);
mImageBitmap = null;
mVideoView.setVisibility(View.VISIBLE);
mImageView.setVisibility(View.INVISIBLE);
mVideoView.start();
saveVideo(mVideoUri);
Log.d("VIDEO INTENT: ", "END OF METHOD");
}
Button.OnClickListener mTakePicOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakePictureIntent(ACTION_TAKE_PHOTO);
}
};
Button.OnClickListener mTakeVidOnClickListener =
new Button.OnClickListener() {
#Override
public void onClick(View v) {
dispatchTakeVideoIntent();
}
};
// Intent data is how the photo and video transfer into their views
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTION_TAKE_PHOTO: {
if (resultCode == RESULT_OK) {
handleCameraPhoto();
}
break;
} // ACTION_TAKE_PHOTO
case ACTION_TAKE_VIDEO: {
if (resultCode == RESULT_OK) {
handleCameraVideo(data);
}
break;
} // ACTION_TAKE_VIDEO
} // switch
}
// Some lifecycle callbacks so that the image can survive orientation change
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelable(BITMAP_STORAGE_KEY, mImageBitmap);
outState.putParcelable(VIDEO_STORAGE_KEY, mVideoUri);
outState.putBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY, (mImageBitmap != null) );
outState.putBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY, (mVideoUri != null) );
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mImageBitmap = savedInstanceState.getParcelable(BITMAP_STORAGE_KEY);
mVideoUri = savedInstanceState.getParcelable(VIDEO_STORAGE_KEY);
mImageView.setImageBitmap(mImageBitmap);
mImageView.setVisibility(
savedInstanceState.getBoolean(IMAGEVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
mVideoView.setVideoURI(mVideoUri);
mVideoView.setVisibility(
savedInstanceState.getBoolean(VIDEOVIEW_VISIBILITY_STORAGE_KEY) ?
ImageView.VISIBLE : ImageView.INVISIBLE
);
}
/**
* Indicates whether the specified action can be used as an intent. This
* method queries the package manager for installed packages that can
* respond to an intent with the specified action. If no suitable package is
* found, this method returns false.
* http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
*
* #param context The application's environment.
* #param action The Intent action to check for availability.
*
* #return True if an Intent with the specified action can be sent and
* responded to, false otherwise.
*/
public static boolean isIntentAvailable(Context context, String action) {
final PackageManager packageManager = context.getPackageManager();
final Intent intent = new Intent(action);
List<ResolveInfo> list =
packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
private void setBtnListenerOrDisable(
Button btn,
Button.OnClickListener onClickListener,
String intentName
) {
if (isIntentAvailable(this, intentName)) {
btn.setOnClickListener(onClickListener);
} else {
btn.setText(
getText(R.string.cannot).toString() + " " + btn.getText());
btn.setClickable(false);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Makes the UP caret go back to the previous fragment MakeCuteFragment
switch (item.getItemId()) {
case android.R.id.home:
android.app.FragmentManager fm= getFragmentManager();
fm.popBackStack();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Just update the lines in dispatchTakeVideoIntent()
provide a proper path to create fileVideo first and make sure to call createNewFile() before putting in intent.

Tesseract - Help me understand datapath

Can someone explain what exactly is going on and how I can rectify it. So I understand tesseract has to have an image to target and presumably this would be the bitmap I've captured and tried to save. That saved location would be my _path variable. Now what is the DATA_PATH for tesseract? Does the image need to be stored in a folder called 'tesseract' ? Do I create that folder and store some kind of training in it? I'm looking for an explanation rather than a code example.
http://gaut.am/making-an-ocr-android-app-using-tesseract/ - I am trying to follow this tutorial and checking others to try and understand the paths which all of them use.
public class MainActivity extends Activity {
private static ImageView imageView;
protected String _path;
// protected static Bitmap bit;
static File myDir;
protected static Bitmap mImageBitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.imageView = (ImageView) this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
_path = Environment.getExternalStorageDirectory() + "/images/test.bmp";
Toast t = Toast.makeText(getApplicationContext(), "HEELLLLLLOO", 100000);
t.show();
photoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// CALL THE PICTURE
dispatchTakePictureIntent(0);
}
});
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(mImageBitmap);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile( _path, options );
imageView.setImageBitmap(bitmap);
//_path = path to the image to be OCRed
ExifInterface exif;
try {
exif = new ExifInterface(_path);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
int rotate = 0;
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
}
if (rotate != 0) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
// Setting pre rotate
Matrix mtx = new Matrix();
mtx.preRotate(rotate);
// Rotating Bitmap & convert to ARGB_8888, required by tess
bitmap = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
}
TessBaseAPI baseApi = new TessBaseAPI();
// DATA_PATH = Path to the storage
// lang for which the language data exists, usually "eng"
baseApi.init(_path, "eng"); //THIS SHOULD BE DATA_PATH ?
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
System.out.println(recognizedText);
baseApi.end();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
handleSmallCameraPhoto(data);
}
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
}
protected static void identifyunicode() {
// DATA_PATH = Path to the storage
// lang for which the language data exists, usually "eng"
/*
* TessBaseAPI baseApi = new TessBaseAPI();
* baseApi.init(myDir.toString(), "eng"); // myDir + //
* "/tessdata/eng.traineddata" // must be present baseApi.setImage(bit);
* String recognizedText = baseApi.getUTF8Text(); // Log or otherwise //
* display this // string... baseApi.end();
*/
}
}
DataPath is the path where you copied your tessdata files from Assets.
import java.io.File;
import java.util.ArrayList;
import android.os.Environment;
public class Utils {
public static boolean isSDCardMounted() {
boolean isMounted = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
isMounted = true;
} else if (Environment.MEDIA_BAD_REMOVAL.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_CHECKING.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_NOFS.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_REMOVED.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_UNMOUNTABLE.equals(state)) {
isMounted = false;
} else if (Environment.MEDIA_UNMOUNTED.equals(state)) {
isMounted = false;
}
return isMounted;
}
public static boolean isDirectoryExists(final String filePath) {
boolean isDirectoryExists = false;
File mFilePath = new File(filePath);
if(mFilePath.exists()) {
isDirectoryExists = true;
} else {
isDirectoryExists = mFilePath.mkdirs();
}
return isDirectoryExists;
}
public static boolean deleteFile(final String filePath) {
boolean isFileExists = false;
File mFilePath = new File(filePath);
if(mFilePath.exists()) {
mFilePath.delete();
isFileExists = true;
}
return isFileExists;
}
public static String getDataPath() {
String returnedPath = "";
final String mDirName = "tesseract";
final String mDataDirName = "tessdata";
if(isSDCardMounted()) {
final String mSDCardPath = Environment.getExternalStorageDirectory() + File.separator + mDirName;
if(isDirectoryExists(mSDCardPath)) {
final String mSDCardDataPath = Environment.getExternalStorageDirectory() + File.separator + mDirName +
File.separator + mDataDirName;
isDirectoryExists(mSDCardDataPath);
return mSDCardPath;
}
}
return returnedPath;
}
}
Activity Class
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.TextView;
import com.googlecode.tesseract.android.TessBaseAPI;
public class AndroidCommonTest extends Activity {
private static final String TAG = AndroidCommonTest.class.getSimpleName();
private TextView txtGotTime = null;
private final int START_CODE = 101;
private String mDirPath = null;
private Uri mOutPutUri = null;
private static final String lang = "eng";
private String mPath = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtGotTime = (TextView) findViewById(R.id.txtGotTime);
mDirPath = Utils.getDataPath();
mPath = mDirPath + File.separator + "test.jpg";
android.util.Log.i(TAG, "mDirPath: " + mDirPath + " mPath: " + mPath);
if (!(new File(mDirPath + File.separator + "tessdata" + File.separator + lang + ".traineddata")).exists()) {
try {
AssetManager assetManager = getAssets();
InputStream in = assetManager.open("tessdata" + File.separator + lang + ".traineddata");
OutputStream out = new FileOutputStream(mDirPath + File.separator
+ "tessdata" + File.separator + lang + ".traineddata");
byte[] buf = new byte[8024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Was unable to copy " + lang + " traineddata " + e.toString());
}
} else {
processImage(mDirPath + File.separator + "six.jpg", 0);
}
}
public void getTime(View view) {
android.util.Log.i(TAG, "mDirPath: " + mDirPath + " mPath: " + mPath);
if(mDirPath != null && mDirPath.length() > 0) {
mOutPutUri = Uri.fromFile(new File(mPath));
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mOutPutUri);
startActivityForResult(intent, START_CODE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == START_CODE) {
if(resultCode == Activity.RESULT_OK) {
int rotation = -1;
long fileSize = new File(mPath).length();
android.util.Log.i(TAG, "fileSize " + fileSize);
//Suppose Device Supports ExifInterface
ExifInterface exif;
try {
exif = new ExifInterface(mPath);
int exifOrientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (exifOrientation) {
case ExifInterface.ORIENTATION_ROTATE_90 :
rotation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180 :
rotation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270 :
rotation = 270;
break;
case ExifInterface.ORIENTATION_NORMAL:
case ExifInterface.ORIENTATION_UNDEFINED:
rotation = 0;
break;
}
android.util.Log.i(TAG, "Exif:rotation " + rotation);
if (rotation != -1) {
processImage(mPath, rotation);
} else {
//Device Does Not Support ExifInterface
Cursor mediaCursor = getContentResolver().query(mOutPutUri,
new String[] { MediaStore.Images.ImageColumns.ORIENTATION,
MediaStore.MediaColumns.SIZE },
null, null, null);
if (mediaCursor != null && mediaCursor.getCount() != 0 ) {
while(mediaCursor.moveToNext()){
long size = mediaCursor.getLong(1);
android.util.Log.i(TAG, "Media:size " + size);
if(size == fileSize){
rotation = mediaCursor.getInt(0);
break;
}
}
android.util.Log.i(TAG, "Media:rotation " + rotation);
processImage(mPath, rotation);
} else {
android.util.Log.i(TAG, "Android Problem");
txtGotTime.setText("Android Problem");
}
}
}
catch (IOException exception) {
exception.printStackTrace();
}
} else if(resultCode == Activity.RESULT_CANCELED) {
android.util.Log.i(TAG, "RESULT_CANCELED");
txtGotTime.setText("RESULT_CANCELED");
}
}
}
private void processImage(final String filePath, final int rotation) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
if (bitmap != null) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, false);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
TessBaseAPI baseApi = new TessBaseAPI();
baseApi.setDebug(true);
baseApi.init(mDirPath, lang);
baseApi.setPageSegMode(100);
baseApi.setPageSegMode(7);
baseApi.setImage(bitmap);
String recognizedText = baseApi.getUTF8Text();
android.util.Log.i(TAG, "recognizedText: 1 " + recognizedText);
baseApi.end();
if(lang.equalsIgnoreCase("eng")) {
recognizedText = recognizedText.replaceAll("[^a-zA-Z0-9]+", " ");
}
android.util.Log.i(TAG, "recognizedText: 2 " + recognizedText.trim());
txtGotTime.setText(recognizedText.trim());
}
}
private void saveImageAndroid(final Bitmap passedBitmap) {
try {
FileOutputStream mFileOutStream = new FileOutputStream(mDirPath + File.separator + "savedAndroid.jpg");
passedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, mFileOutStream);
mFileOutStream.flush();
mFileOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Put tessdata folder in Assets.
Do not forget to give reference path of Tess Library.
Thanks.

Android image from gallery wrong orientation

I am using an intent to load an image from the Android gallery. On a few of the devices I have tried it works fine but it seems on some devices the images loads in the wrong orientation. It's usually displayed in landscape instead of portrait.
I did some searching and found a few suggestions regarding EXIF data and tried the following:
if(resultCode == RESULT_OK){
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 filePath = cursor.getString(columnIndex);
cursor.close();
String myFile = selectedImage.toString();
int orientation = 0;
try {
ExifInterface exif = new ExifInterface(myFile);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
} catch (IOException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
Bitmap rotatedBitmap = null;
Matrix matrix = new Matrix();
switch(orientation){
case 3:
matrix.postRotate(180);
break;
case 6:
matrix.postRotate(90);
break;
case 8:
matrix.postRotate(270);
break;
}
rotatedBitmap = Bitmap.createBitmap(yourSelectedImage, 0, 0, yourSelectedImage.getWidth(), yourSelectedImage.getHeight(), matrix, true);
_mJazzView.setBackground(rotatedBitmap);
}
This did not resolve the issue and after trying several variations from further searching I can't seem to get it to load in the correct orientation.
Any help would be great!
Hopefully it isn't too late to help! I have ran into this issue, I think a lot of people are unaware of it because they don't have many devices to test across. Anyway, here is the solution I have found by looking into the classes of this crop lib https://github.com/jdamcd/android-crop which is based on AOSP. This is a copy paste job so it should all be very easy to get into your project. Apologies for the formatting, I wrestled with this comment box and lost.
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent,"whatever you want",1);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode)
{
case 1:
if (resultCode == RESULT_OK)
{
Uri selectedImage = data.getData();
int rotationInDegrees = getRotationInDegrees(selectedImage);
}
break;
}
}
private int getRotationInDegrees(Uri uri)
{
return ImageOrientationUtil
.getExifRotation(ImageOrientationUtil
.getFromMediaUri(
this,
getContentResolver(),
uri));
}
ImageOrientationUtil.class
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import java.io.Closeable;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class ImageOrientationUtil
{
private static final String SCHEME_FILE = "file";
private static final String SCHEME_CONTENT = "content";
public static void closeSilently(#Nullable Closeable c) {
if (c == null) return;
try {
c.close();
} catch (Throwable t) {
// Do nothing
}
}
public static int getExifRotation(File imageFile) {
if (imageFile == null) return 0;
try {
ExifInterface exif = new ExifInterface(imageFile.getAbsolutePath());
// We only recognize a subset of orientation tag values
switch (exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED)) {
case ExifInterface.ORIENTATION_ROTATE_90:
return 90;
case ExifInterface.ORIENTATION_ROTATE_180:
return 180;
case ExifInterface.ORIENTATION_ROTATE_270:
return 270;
default:
return ExifInterface.ORIENTATION_UNDEFINED;
}
} catch (IOException e) {
// Log.e("Error getting Exif data", e);
return 0;
}
}
#Nullable
public static File getFromMediaUri(Context context,
ContentResolver resolver, Uri uri) {
if (uri == null) return null;
if (SCHEME_FILE.equals(uri.getScheme())) {
return new File(uri.getPath());
} else if (SCHEME_CONTENT.equals(uri.getScheme())) {
final String[] filePathColumn = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DISPLAY_NAME };
Cursor cursor = null;
try {
cursor = resolver.query(uri, filePathColumn, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final int columnIndex = (uri.toString().startsWith("content://com.google.android.gallery3d")) ?
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME) :
cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
// Picasa images on API 13+
if (columnIndex != -1) {
String filePath = cursor.getString(columnIndex);
if (!TextUtils.isEmpty(filePath)) {
return new File(filePath);
}
}
}
} catch (IllegalArgumentException e) {
// Google Drive images
return getFromMediaUriPfd(context, resolver, uri);
} catch (SecurityException ignored) {
// Nothing we can do
} finally {
if (cursor != null) cursor.close();
}
}
return null;
}
private static String getTempFilename(Context context) throws IOException {
File outputDir = context.getCacheDir();
File outputFile = File.createTempFile("image", "tmp", outputDir);
return outputFile.getAbsolutePath();
}
#Nullable
private static File getFromMediaUriPfd(Context context, ContentResolver resolver, Uri uri) {
if (uri == null) return null;
FileInputStream input = null;
FileOutputStream output = null;
try {
ParcelFileDescriptor pfd = resolver.openFileDescriptor(uri, "r");
FileDescriptor fd = pfd.getFileDescriptor();
input = new FileInputStream(fd);
String tempFilename = getTempFilename(context);
output = new FileOutputStream(tempFilename);
int read;
byte[] bytes = new byte[4096];
while ((read = input.read(bytes)) != -1) {
output.write(bytes, 0, read);
}
return new File(tempFilename);
} catch (IOException ignored) {
// Nothing we can do
} finally {
closeSilently(input);
closeSilently(output);
}
return null;
}
}

Categories

Resources