I'm building a GIF Creator for my graduation project. What it is, when I try to select from the gallery a photo it just gets it to the view, I want to select more than one photo simultaneously not to go to select photo to get another picture. As well as that I've created a button so if the user changes their mind they can delete and start from scratch not having to restart the application however I don't know what the code is for that.
The main activity:
public class MainActivity extends AppCompatActivity {
/**
* this is the destination of the new GIF file, it will be saved directly in the SD card
* (internal storage) in a file named "test.gif"
*/
private static final String IMAGE_PATH = "/sdcard/test.gif";
private static final int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private boolean zoomOut = false;
private Button btnSelect;
private LinearLayout root;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
btnSelect = (Button) findViewById(R.id.btnSelectPhoto);
root = (LinearLayout) findViewById(R.id.ll);
btnSelect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImage();
}
});
ImageView ivImage = (ImageView) findViewById(R.id.ivImage);
ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (root.getChildCount() == 0) {
return;
}
FileOutputStream outStream = null;
try {
outStream = new FileOutputStream(IMAGE_PATH);
outStream.write(generateGIF());
outStream.close();
Toast.makeText(MainActivity.this,
"GIF saved to " + IMAGE_PATH, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outStream != null) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
});
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/* video/*");
startActivityForResult(
Intent.createChooser(intent, "Select File"),
SELECT_FILE);
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
Bitmap resized = Bitmap.createScaledBitmap(thumbnail, 800, 150, true);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ImageView ivImage = new ImageView(this);
GradientDrawable gd = new GradientDrawable();
gd.setColor(0xFF00FF00); // Changes this drawbale to use a single color instead of a gradient
gd.setCornerRadius(5);
gd.setStroke(1, 0xFF000000);
ivImage.setBackground(gd);
// the following code causes a crash "NullPointerException" :
// Point point = null; // --> the reason for the crash
// getWindowManager().getDefaultDisplay().getSize(point);
// int width = point.x;
// int height = point.y;
//
// ivImage.setMinimumWidth(width);
// ivImage.setMinimumHeight(height);
//
// ivImage.setMaxWidth(width);
// ivImage.setMaxHeight(height);
// ivImage.getLayoutParams().width = 20; // --> another crash happens here
// ivImage.getLayoutParams().height = 20;
ivImage.setLayoutParams(new ActionBar.LayoutParams(
GridLayout.LayoutParams.WRAP_CONTENT,
GridLayout.LayoutParams.MATCH_PARENT));
ivImage.setImageBitmap(thumbnail);
root.addView(ivImage);
// setContentView(root);
// ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Uri selectedImageUri = data.getData();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cursor = managedQuery(selectedImageUri, projection, null, null,
null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
String selectedImagePath = cursor.getString(column_index);
Bitmap bm;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(selectedImagePath, options);
final int REQUIRED_SIZE = 200;
int scale = 1;
while (options.outWidth / scale / 2 >= REQUIRED_SIZE
&& options.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
options.inSampleSize = scale;
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(selectedImagePath, options);
final ImageView ivImage = new ImageView(this);
ivImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (zoomOut) {
Toast.makeText(getApplicationContext(), "NORMAL SIZE!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ivImage.setAdjustViewBounds(true);
zoomOut = false;
} else {
Toast.makeText(getApplicationContext(), "FULLSCREEN!", Toast.LENGTH_LONG).show();
ivImage.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
ivImage.setScaleType(ImageView.ScaleType.FIT_XY);
zoomOut = true;
}
}
});
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
ivImage.setMinimumWidth(width);
ivImage.setMinimumHeight(height);
ivImage.setMaxWidth(width);
ivImage.setMaxHeight(height);
ivImage.setLayoutParams(new ActionBar.LayoutParams(
1000,
1000));
ivImage.setImageBitmap(bm);
root.addView(ivImage);
setContentView(root);
ivImage.setImageBitmap(bm);
}
private byte[] generateGIF() {
ArrayList<Bitmap> bitmaps = new ArrayList<>();
View v;
ImageView iv;
for (int i = 0; i < root.getChildCount(); i++) {
v = root.getChildAt(i);
if (v instanceof ImageView) {
iv = (ImageView) v;
bitmaps.add(((BitmapDrawable) iv.getDrawable()).getBitmap());
}
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
AnimatedGifEncoder encoder = new AnimatedGifEncoder();
encoder.start(bos);
for (Bitmap bitmap : bitmaps) {
encoder.addFrame(bitmap);
}
encoder.finish();
return bos.toByteArray();
}
}
You can use custom library for multiple image pick like
1) MultiSelectRecyclerGalleryGridView
2) MultipleImagePick
like Kyle Shank answered
https://stackoverflow.com/a/19848052/5090511
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
Or you can use something like that:
https://github.com/luminousman/MultipleImagePick
Related
Hi can someone help me how can I add to pdf the selected images from gallery? I already have working code but it can only convert one bitmap.
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void createPdf(){
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = displaymetrics.heightPixels ;
float width = displaymetrics.widthPixels ;
int convertHighet = (int) hight, convertWidth = (int) width;
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0 , null);
document.finishPage(page);
// write the document content
String targetPdf = "/sdcard/test.pdf";
File filePath = new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
btn_convert.setText("Check PDF");
boolean_save=true;
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
document.close();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICTURE && resultCode == RESULT_OK) {
if (resultCode == RESULT_OK) {
Uri uri = data.getData();
if(uri != null) {
Cursor cursor = getContentResolver().query(uri, new String[] {
android.provider.MediaStore.Images.ImageColumns.DATA},
null, null, null);
cursor.moveToFirst();
String imageFilePath = cursor.getString(0);
cursor.close();
iv_image.setImageURI(uri);
encodedImage = imageFilePath;
} else {
tv_Load.setText("There's an error");
}
}
}
These are my declarations/fields.
public static final int GALLERY_PICTURE = 1;
public static final int REQUEST_PERMISSIONS = 1;
Button btn_select, btn_convert, btn_upload;
Bitmap bitmap;
Here's my code now that can select Multiple Image but can't convert bitmaps to pdf. It saves but it says PDF is of Invalid Format.
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICTURE && resultCode == RESULT_OK) {
if (resultCode == RESULT_OK) {
final List<Bitmap> bitmaps = new ArrayList<>();
ClipData clipData = data.getClipData();
if (clipData != null) {
for (int i = 0; i < clipData.getItemCount(); i++) {
Uri imageUri = clipData.getItemAt(i).getUri();
try {
InputStream is = getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
bitmaps.add(bitmap);
bitmapcount = clipData.getItemCount();
Toast.makeText(getApplicationContext(),"Image Selected: " + clipData.getItemCount(), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else {
Uri imageUri = data.getData();
try {
InputStream is = getContentResolver().openInputStream(imageUri);
Bitmap bitmap = BitmapFactory.decodeStream(is);
bitmaps.add(bitmap);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
new Thread(new Runnable() {
#Override
public void run() {
for (final Bitmap b : bitmaps) {
runOnUiThread(new Runnable() {
#Override
public void run() {
iv_image.setImageBitmap(b);
}
});
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
private void createPdf(){
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics displaymetrics = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
float hight = displaymetrics.heightPixels ;
float width = displaymetrics.widthPixels ;
int convertHighet = (int) hight, convertWidth = (int) width;
PdfDocument document = new PdfDocument();
if (bitmapcount > 1){
for(int i = 0; i < bitmapcount; i++ ){
try {
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), i).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0 , null);
document.finishPage(page);
i++;
} catch (Exception e){
e.printStackTrace();
}
}
}
//document content311
String directory_path = Environment.getExternalStorageDirectory().getPath() + "/mypdf/";
File file = new File(directory_path);
if (!file.exists()) {
file.mkdirs();
}
String targetPdf = directory_path + "JO-" + editText.getText().toString() + ".pdf";
File filePath = new File(targetPdf);
try {
document.writeTo(new FileOutputStream(filePath));
btn_convert.setText("Check PDF");
boolean_save=true;
pdfPath = filePath.getPath();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
}
// close the document
document.close();
}
Fields
private static int bitmapcount = 0;
public static final int GALLERY_PICTURE = 1;
public static final int REQUEST_PERMISSIONS = 1;
Button btn_select, btn_convert, btn_upload;
Bitmap bitmap;
I'm trying to use opencv to detect faces in static pictures from my gallery but i can't manage to detect them (or draw rectangles on the picture). I have tried a lot of things, none of which worked for me. Help would be appreciated.
I have tried changing approaches to detecting the faces, none of which worked.
Logically everything seems fine I think: choose image from gallery ---> detectFaces function ---> setting height and width to each Mat i currently have, converting the imageView's image from bitmap to Mat, so i can work on the Mat to detect the faces and then later convert the Mat back to bitmap to see the results on the imageview (imgview.setImageBitmap(bm)).
public class GalleryDetection extends AppCompatActivity {
private Button button;
private ImageView imgview;
private org.opencv.core.Mat rgba, grayscaleImage;
private CascadeClassifier cascadeClassifier;
private int absoluteFaceSize, mDetectorType = 0;
private DetectionBasedTracker mNativeDetector;
private float mRelativeFaceSize = 0.2f;
static {
System.loadLibrary("opencv_java3");
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this)
{
#Override
public void onManagerConnected(int status) {
switch (status){
case LoaderCallbackInterface.SUCCESS:
rgba = new Mat();
grayscaleImage = new Mat();
MatOfRect faces = new MatOfRect();
initializeOpenCVDependencies();
break;
default:
super.onManagerConnected(status);
break;
}
}
};
private void initializeOpenCVDependencies() {
File cascadeDir = getDir("cascade", Context.MODE_APPEND);
File mCascadeFile = new File(cascadeDir, "lbpcascade frontalface.xml");
cascadeClassifier = new CascadeClassifier(mCascadeFile.getAbsolutePath());
mNativeDetector = new DetectionBasedTracker(mCascadeFile.getAbsolutePath(), 0);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_detection);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
func();
}
void func() {
this.button = (Button) findViewById(R.id.buttonGallery);
this.imgview = (ImageView) findViewById(R.id.imageViewGallery);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 101);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101 && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
String path = getPath(imageUri);
imgview.setImageURI(imageUri);
detectFaces();
}
}
private void detectFaces() {
Bitmap bm = ((BitmapDrawable) imgview.getDrawable()).getBitmap(); // Convert imageview image to bitmap
grayscaleImage = new Mat(bm.getHeight(), bm.getWidth(), CvType.CV_8UC4); // grayImage same size as image view
rgba = new Mat(imgview.getHeight(), imgview.getWidth(), CvType.CV_8UC4); // rgbaImage same size as image view
Utils.bitmapToMat(bm, rgba); // Convert bitmap to Mat
absoluteFaceSize = (int) (bm.getHeight() * 0.2); // set the face size
Utils.matToBitmap(drawRect(rgba), bm); // Convert the Mat with the triangle to bitmap
imgview.setImageBitmap(bm); // Set the image in the imageview to the bitmap with the triangles
}
private String getPath(Uri uri) {
if(uri == null) {
return null;
}
else {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
int col_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(col_index);
}
}
return uri.getPath();
}
public Mat drawRect(Mat rgba) {
Imgproc.cvtColor(rgba, grayscaleImage, Imgproc.COLOR_RGBA2RGB); // Convert colors (not really sure how and why it's here)
if(absoluteFaceSize == 0) {
int height = grayscaleImage.rows();
if(Math.round(height * mRelativeFaceSize) > 0) {
absoluteFaceSize = Math.round(height * mRelativeFaceSize);
}
mNativeDetector.setMinFaceSize(absoluteFaceSize);
}
MatOfRect faces = new MatOfRect();
if (mDetectorType == 0) {
if (cascadeClassifier != null) {
cascadeClassifier.detectMultiScale(grayscaleImage, faces, 1.1,2,2,
new Size(absoluteFaceSize, absoluteFaceSize), new Size());
}
}
else if (mDetectorType == 1) {
if (mNativeDetector != null) {
mNativeDetector.detect(grayscaleImage, faces);
}
}
Rect[] facesArray = faces.toArray();
for (int i = 0; i < facesArray.length; i++) {
Imgproc.rectangle(rgba, facesArray[i].tl(), facesArray[i].br(), new Scalar(255, 0, 0), 3);
}
return rgba;
}
}
Expected result: Image's faces are surrounded by rectangles
Actual result: Image showing without any rectangles
[][1[After Doing this changes Working fine this code.
I got Image's faces are surrounded by rectangles
Note:-
1.In Android Studio, go to File > New > Import-Module and the choose /sdk and wait for the sync to finish.
2.Do not import /sdk/java like most tutorials suggest.
public class GalleryDetection extends AppCompatActivity {
private static final Scalar FACE_RECT_COLOR = new Scalar(0, 255, 0, 255);
private Button button, btnFaceDetect;
private ImageView imgview;
private AppCompatImageView imgview2;
private org.opencv.core.Mat rgba, grayscaleImage;
private CascadeClassifier cascadeClassifier;
private int absoluteFaceSize = 0, mDetectorType = 0;
private float mRelativeFaceSize = 0.2f;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
rgba = new Mat();
grayscaleImage = new Mat();
initializeOpenCVDependencies();
break;
default:
try {
super.onManagerConnected(status);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
};
private void initializeOpenCVDependencies() {
File cascadeDir = getDir("cascade", Context.MODE_APPEND);
File mCascadeFile = new File(cascadeDir, "lbpcascade_frontalface.xml");
cascadeClassifier = new CascadeClassifier(mCascadeFile.getAbsolutePath());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_detection);
if (!OpenCVLoader.initDebug()) {
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION, this, mLoaderCallback);
} else {
try {
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
} catch (IOException e) {
e.printStackTrace();
}
}
func();
}
void func() {
this.button = (Button) findViewById(R.id.btngallery);
this.btnFaceDetect = (Button) findViewById(R.id.btnselect);
this.imgview = (ImageView) findViewById(R.id.imageview);
this.imgview2 = findViewById(R.id.imageview2);
btnFaceDetect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
detectFaces();
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imgview.setImageResource(R.drawable.ic_launcher_foreground);
imgview2.setImageResource(R.drawable.ic_launcher_foreground);
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 101);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 101 && resultCode == RESULT_OK && data != null) {
Uri imageUri = data.getData();
try {
imgview.setImageURI(imageUri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void detectFaces() {
ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Loading, please wait...");
dialog.show();
Bitmap bm = ((BitmapDrawable) imgview.getDrawable()).getBitmap();// Convert imageview image to bitmap
grayscaleImage = new Mat(bm.getHeight(), bm.getWidth(), CvType.CV_8UC4); // grayImage same size as image view
rgba = new Mat(imgview2.getHeight(), imgview2.getWidth(), CvType.CV_8UC4); // rgbaImage same size as image view
Utils.bitmapToMat(bm, rgba); // Convert bitmap to Mat
absoluteFaceSize = (int) (bm.getHeight() * 0.2); // set the face size
Utils.matToBitmap(drawRect(rgba), bm);// Convert the Mat with the triangle to bitmap
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Bitmap pass = null;
//Convert to byte array
pass = bm;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
pass.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byteArray = stream.toByteArray();
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
imgview2.setImageBitmap(bmp);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}, 1000);
// Set the image in the imageview to the bitmap with the triangles
}
public Mat drawRect(Mat rgba) {
Imgproc.cvtColor(rgba, grayscaleImage, Imgproc.COLOR_RGBA2RGB); // Convert colors (not really sure how and why it's here)
if (absoluteFaceSize == 0) {
int height = grayscaleImage.rows();
if (Math.round(height * mRelativeFaceSize) > 0) {
absoluteFaceSize = Math.round(height * mRelativeFaceSize);
}
}
if (mDetectorType == 0) {
if (cascadeClassifier != null) {
MatOfRect feceDetection = new MatOfRect();
cascadeClassifier.detectMultiScale(rgba, feceDetection, 1.1, 7, 2);
for (Rect rect : feceDetection.toArray()) {
Imgproc.rectangle(rgba, new Point(rect.x, rect.y),
new Point(rect.x + rect.width, rect.y + rect.height),
FACE_RECT_COLOR, 3, 2);
}
}
}
return rgba;
}
}
I have an error whenever I try to take a picture by using camera intent.
This is the error
FileNotFoundException: No files supported by provider at content://com.example.fahad.inventory/my_images/dcim/Inventory/JPEG20170922_170324_1975076666.jpg
at com.example.fahad.inventory.AddProductActivity.getBitmap(AddProductActivity.java:270) 09-22 17:03:30.117 12950-12950/? W/System.err: at com.example.fahad.inventory.AddProductActivity.onActivityResult(AddProductActivity.java:197)
This is my code
public class AddProductActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int REQUEST_SELECT_IMAGE = 2;
private static final String IMAGE_PATH = "imagePath";
private static final String IMAGE_URI = "imageUri";
private static final String BITMAP = "bitmap";
private static final String CAMERA_DIR = "/dcim/";
private String imagePath = "";
private String imageUri = "";
private ImageView imageView;
private Bitmap bitmap;
private Uri mUri;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
Button addProduct = (Button) findViewById(R.id.id_btn_add_product);
Button addImage = (Button) findViewById(R.id.id_btn_add_image);
Button addGalleryImage = (Button) findViewById(R.id.id_btn_add_gallery_image);
imageView = (ImageView) findViewById(R.id.id_image_view);
if (savedInstanceState != null) {
imagePath = savedInstanceState.getString(IMAGE_PATH);
imageUri = savedInstanceState.getString(IMAGE_URI);
bitmap = (Bitmap) savedInstanceState.get(BITMAP);
imageView.setImageBitmap(bitmap);
}
addProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
insert();
}
});
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
File f = createImageFile();
mUri = FileProvider.getUriForFile(
AddProductActivity.this, ProductContract.CONTENT_AUTHORITY, f);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
// Solution taken from http://stackoverflow.com/a/18332000/3346625
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, mUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
addGalleryImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
} else {
intent = new Intent(Intent.ACTION_GET_CONTENT);
}
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select image"), REQUEST_SELECT_IMAGE);
}
});
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG" + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, ".jpg", albumF);
return imageF;
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStorageDirectory()
+ CAMERA_DIR
+ getString(R.string.app_name));
if (storageDir != null) {
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
public void insert() {
EditText editProductName = (EditText) findViewById(R.id.id_edit_product_name);
EditText editProductPrice = (EditText) findViewById(R.id.id_edit_product_price);
EditText editProductQuantity = (EditText) findViewById(R.id.id_edit_product_quantity);
String name = editProductName.getText().toString();
String quantity = editProductQuantity.getText().toString();
String price = editProductPrice.getText().toString();
ContentValues values = new ContentValues();
values.put(ProductContract.ProductColumns.PRODUCT_NAME, name);
values.put(ProductContract.ProductColumns.PRODUCT_QUANTITY, quantity);
values.put(ProductContract.ProductColumns.PRODUCT_PRICE, price);
values.put(ProductContract.ProductColumns.PRODUCT_IMAGE_PATH, imagePath);
values.put(ProductContract.ProductColumns.PRODUCT_IMAGE_URI, imagePath);
Uri uri = getContentResolver().insert(ProductContract.ProductColumns.CONTENT_URI, values);
if (uri != null) {
finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
imageUri = mUri.getPath();
bitmap = getBitmap(mUri);
imageView.setImageBitmap(bitmap);
} else if (requestCode == REQUEST_SELECT_IMAGE && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = data.getData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final int flags = data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION;
ContentResolver contentResolver = getContentResolver();
contentResolver.takePersistableUriPermission(uri, flags);
}
imageView.setImageBitmap(getBitmapFromUri(uri));
imageUri = uri.toString();
imagePath = uri.toString();
}
}
}
public Bitmap getBitmapFromUri(Uri uri) {
if (uri == null || uri.toString().isEmpty())
return null;
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
InputStream input = null;
try {
input = this.getContentResolver().openInputStream(uri);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, bmOptions);
input.close();
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
input = this.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
input.close();
return bitmap;
} catch (FileNotFoundException fne) {
fne.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
input.close();
} catch (IOException ioe) {
}
}
}
private Bitmap getBitmap(Uri uri) {
ParcelFileDescriptor parcelFileDescriptor = null;
try {
parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (parcelFileDescriptor != null) {
parcelFileDescriptor.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(IMAGE_PATH, imagePath);
outState.putString(IMAGE_URI, imageUri);
outState.putParcelable(BITMAP, bitmap);
}
The contentAuthority is my package name.
com.example.fahad.inventory
And this is my paths :
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="my_images" />
</paths>
And this is my provider in manifest :
<provider
android:name=".data.ProductProvider"
android:authorities="com.example.fahad.inventory"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
</provider>
I have seen some posts like this by I don't understands it. or it didn't help me with my problem.
The error in the logs are pointing to :
getContentResolver().openFileDescriptor(uri, "r");
Also the data returned in onActivityResult from the camera is always null.
I think the problem is I have to implement OpenFile method in my custom contentProvider but the problem I don't know what to write in that method.
Or the getUriForFile return wrong uri.
Please help me I'm in this problem for two weeks now and it seems I'm not going anywhere.
And I'm new to contentProvider.
Thanks in Advance And happy coding !
Currently looking for help on saving images from a camera app to internal storage do to Nexus not having an SD card, our current code saves the photos taken to an SD card folder and the quality is not good.
public class MainActivity extends ActionBarActivity {
private ImageView imageHolder;
private final int requestCode = 20;
public final static String EXTRA_MESSAGE = "com.test1.cam.camapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
// display the image from SD Card to ImageView Control
String storeFilename = "photo_" + partFilename + ".jpg";
Bitmap mBitmap = getImageFileFromSDCard(storeFilename);
imageHolder.setImageBitmap(mBitmap);
}
}
public void showGreetings(View view)
{
String button_text;
button_text = ((Button) view) .getText().toString();
if(button_text.equals("Info"))
{
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
else if (button_text.equals("Info"))
{
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
}
public void saveImage(Context context, Bitmap b,String name,String extension){
name=name+"."+extension;
FileOutputStream out;
try {
out = context.openFileOutput(name, Context.MODE_PRIVATE);
b.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Bitmap getImageFileFromSDCard(String filename){
Bitmap bitmap = null;
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
try {
FileInputStream fis = new FileInputStream(imageFile);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
To improve the image quality you should change compression to PNG, or change the second parameters to 100 (PNG is lossless and will ignore second params).
b.compress(Bitmap.CompressFormat.PNG, 100, out);
To change external into internal just change
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
into
File outputFile = new File(context.getFilesDir(), "photo_" + currentDate + ".jpg");
The image you are trying to save returns you jest the thumbnail of the actual image that is why you are getting low quality image. You should pass the image name to the intent to save the high quality image when it is captured
Following Helper class that I use for image capture may be of some help to you
public class CaptureImageHelper {
private static final int DEFAULT_WIDTH = 1024; // min pixels
private static final int DEFAULT_HEIGHT = 768; // min pixels
private static final String TEMP_IMAGE_NAME = "tempImage";
public static Intent getImageCaptureIntent(Context context, String title) {
Intent chooserIntent = null;
List<Intent> intentList = new ArrayList<>();
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(getTempFile(context)));
intentList = addIntentsToList(context, intentList, takePhotoIntent);
if (intentList.size() > 0) {
chooserIntent = Intent.createChooser(intentList.remove(intentList.size() - 1), title);
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentList.toArray(new Parcelable[]{}));
}
return chooserIntent;
}
private static File getTempFile(Context context) {
//Note you can change the path here according to your need
File imageFile = new File(Environment.getExternalStorageDirectory(), TEMP_IMAGE_NAME);
imageFile.getParentFile().mkdirs();
return imageFile;
}
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);
}
return list;
}
public static Bitmap getImageFromResult(Context context, int resultCode, Intent imageReturnedIntent) {
return getImageFromResult(context, DEFAULT_WIDTH, DEFAULT_HEIGHT, resultCode, imageReturnedIntent);
}
public static Bitmap getImageFromResult(Context context, int width, int height, int resultCode, Intent imageReturnedIntent) {
Bitmap bm = null;
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage;
File imageFile = getTempFile(context);
selectedImage = Uri.fromFile(imageFile);
bm = getImageResized(context, selectedImage, width, height);
int rotation = getRotation(context, selectedImage, true);
bm = rotate(bm, rotation);
}
return bm;
}
private static Bitmap getImageResized(Context context, Uri selectedImage, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
System.gc();
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap actuallyUsableBitmap = null;
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(selectedImage, "r");
} catch (FileNotFoundException e) {
}
if (null != fileDescriptor) {
BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
actuallyUsableBitmap = BitmapFactory.decodeFileDescriptor(fileDescriptor.getFileDescriptor(), null, options);
}
return actuallyUsableBitmap;
}
private static Bitmap getImageResized(Context context, Uri selectedImage) {
return getImageResized(context, selectedImage, DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
private static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
private static int getRotation(Context context, Uri imageUri, boolean isCamera) {
int rotation;
if (isCamera) {
rotation = getRotationFromCamera(context, imageUri);
} else {
rotation = getRotationFromGallery(context, imageUri);
}
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;
}
private static int getRotationFromGallery(Context context, Uri imageUri) {
int orientation = 0;
String[] columns = {MediaStore.Images.Media.ORIENTATION};
Cursor cursor = context.getContentResolver().query(imageUri, columns, null, null, null);
if (null != cursor && cursor.moveToFirst()) {
int orientationColumnIndex = cursor.getColumnIndex(columns[0]);
orientation = cursor.getInt(orientationColumnIndex);
cursor.close();
}
return orientation;
}
private static Bitmap rotate(Bitmap bm, int rotation) {
if (rotation != 0) {
Matrix matrix = new Matrix();
matrix.postRotate(rotation);
return Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
}
return bm;
}
}
I am using the takePicture function in the Camera to continuously take and store pictures on a tablet. I need to know how I can crop the data that is stored upon calling takePicture. Or, if that is not possible, then I need to know how I can read in an image and then use something else to crop it. So far the only solutions I've found to this problem require opening another app to crop. Any help is appreciated.
You can try below code to crop the image:
final String Path = "sdcard/test.jpg";
Bitmap bitmap = BitmapFactory.decodeFile(Path);
ivSign.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 150, 150, true));
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(Uri.fromFile(new File(Path)), "image/*");
// set crop properties
cropIntent.putExtra("crop", "true");
// indicate aspect of desired crop
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
// indicate output X and Y
cropIntent.putExtra("outputX", 256);
cropIntent.putExtra("outputY", 256);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, 1);
From the Below Code you will get correct Idea. sometimes you will get
Problems if the device is like Samsung Galaxy S3 and you wants to crop image after capturing as they
are returning null intent after capturing image.
After spending hours on this issue i finally make it work by Below Way if some one is having this problem in future.
public class MainActivity extends Activity {
private Uri mImageCaptureUri;
private ImageView mImageView;
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
private String selectedImagePath = "";
boolean GallaryPhotoSelected = false;
public static String Finalmedia = "";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String[] items = new String[] { "Take from camera",
"Select from gallery" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.select_dialog_item, items);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Image");
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) { // pick from
// camera
if (item == 0) {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
// mImageCaptureUri);
// if (hasImageCaptureBug()) {
String path = Environment.getExternalStorageDirectory()
.getName()
+ File.separatorChar
+ System.currentTimeMillis() + ".jpg";
File file = new File(path);
// mImageCaptureUri = Uri.fromFile(new File(
// Environment.getExternalStorageDirectory(),
// "tmp_avatar_"
// + String.valueOf(System
// .currentTimeMillis())
// + ".jpg"));
Log.i("TAG", "Final path" + path);
try {
if (file.exists() == false) {
file.getParentFile().mkdirs();
file.createNewFile();
}
} catch (IOException e) {
Log.e("TAG", "Could not create file.", e);
}
mImageCaptureUri = Uri.fromFile(file);
intent.putExtra(
android.provider.MediaStore.EXTRA_OUTPUT,
mImageCaptureUri);
// } else {
// intent.putExtra(
// android.provider.MediaStore.EXTRA_OUTPUT,
// android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// }
try {
// intent.putExtra("return-data", true);
startActivityForResult(intent, PICK_FROM_CAMERA);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
} else {
new AlertDialog.Builder(MainActivity.this)
.setMessage(
"External Storeage (SD Card) is required.\n\nCurrent state: "
+ storageState)
.setCancelable(true).create().show();
}
} else { // pick from file
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Complete action using"), PICK_FROM_FILE);
}
}
});
final AlertDialog dialog = builder.create();
Button button = (Button) findViewById(R.id.btn_crop);
mImageView = (ImageView) findViewById(R.id.iv_photo);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.show();
}
});
}
public boolean hasImageCaptureBug() {
// list of known devices that have the bug
ArrayList<String> devices = new ArrayList<String>();
devices.add("android-devphone1/dream_devphone/dream");
devices.add("generic/sdk/generic");
devices.add("vodafone/vfpioneer/sapphire");
devices.add("tmobile/kila/dream");
devices.add("verizon/voles/sholes");
devices.add("google_ion/google_ion/sapphire");
return devices.contains(android.os.Build.BRAND + "/"
+ android.os.Build.PRODUCT + "/" + android.os.Build.DEVICE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK)
return;
switch (requestCode) {
case PICK_FROM_CAMERA:
Log.i("TAG", "Inside PICK_FROM_CAMERA");
// mImageCaptureUri = data.getData();
// Bitmap bm1 = (Bitmap) data.getExtras().get("data");
// mImageView.setImageBitmap(bm1);
// Bundle extras1 = data.getExtras();
// Bitmap bm1 = (Bitmap) extras1.get("data");
// mImageView.setImageBitmap(bm1);
/*
* try { if (hasImageCaptureBug()) { Log.i("TAG", "Inside Bug");
* selectedImagePath = String.valueOf(System .currentTimeMillis()) +
* ".jpg"; File fi = new File(
* Environment.getExternalStorageDirectory(), selectedImagePath);
* try { mImageCaptureUri = Uri
* .parse(android.provider.MediaStore.Images.Media
* .insertImage(getContentResolver(), fi.getAbsolutePath(), null,
* null)); if (!fi.delete()) { Log.i("logMarker",
* "Failed to delete " + fi); } } catch (FileNotFoundException e) {
* e.printStackTrace(); } } else { mImageCaptureUri =
* data.getData(); } } catch (Exception e) { Log.i("TAG",
* "Inside Bug"); selectedImagePath =
* String.valueOf(System.currentTimeMillis()) + ".jpg"; File fi =
* new File(Environment.getExternalStorageDirectory(),
* selectedImagePath); try { mImageCaptureUri = Uri
* .parse(android.provider.MediaStore.Images.Media
* .insertImage(getContentResolver(), fi.getAbsolutePath(), null,
* null)); if (!fi.delete()) { Log.i("logMarker",
* "Failed to delete " + fi); } } catch (FileNotFoundException e1) {
* e1.printStackTrace(); } }
*/
String path = mImageCaptureUri.getPath();
Log.i("TAG",
"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!After capture path "
+ path);
doCrop();
break;
case PICK_FROM_FILE:
mImageCaptureUri = data.getData();
Log.i("TAG",
"After Crop mImageCaptureUri " + mImageCaptureUri.getPath());
GallaryPhotoSelected = true;
doCrop();
break;
case CROP_FROM_CAMERA:
Bundle extras = data.getExtras();
selectedImagePath = mImageCaptureUri.getPath();
Log.i("TAG", "After Crop selectedImagePath " + selectedImagePath);
if (GallaryPhotoSelected) {
selectedImagePath = getRealPathFromURI(mImageCaptureUri);
Log.i("TAG", "Absolute Path " + selectedImagePath);
GallaryPhotoSelected = true;
}
Finalmedia = selectedImagePath;
if (extras != null) {
// Bitmap photo = extras.getParcelable("data");
Log.i("TAG", "Inside Extra " + selectedImagePath);
Bitmap photo = (Bitmap) extras.get("data");
selectedImagePath = String.valueOf(System.currentTimeMillis())
+ ".jpg";
Log.i("TAG", "new selectedImagePath before file "
+ selectedImagePath);
File file = new File(Environment.getExternalStorageDirectory(),
selectedImagePath);
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
photo.compress(Bitmap.CompressFormat.PNG, 95, fos);
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(this,
"Sorry, Camera Crashed-Please Report as Crash A.",
Toast.LENGTH_LONG).show();
}
selectedImagePath = Environment.getExternalStorageDirectory()
+ "/" + selectedImagePath;
Log.i("TAG", "After File Created " + selectedImagePath);
Bitmap bm = decodeFile(selectedImagePath);
mImageView.setImageBitmap(bm);
}
/*
* File f = new File(mImageCaptureUri.getPath());
*
* if (f.exists()) f.delete();
*/
break;
}
}
public static Bitmap decodeFile(String path) {
int orientation;
try {
if (path == null) {
return null;
}
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 70;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
// while (true) {
// if (width_tmp / 2 < REQUIRED_SIZE
// || height_tmp / 2 < REQUIRED_SIZE)
// break;
// width_tmp /= 2;
// height_tmp /= 2;
// scale++;
// }
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap bm = BitmapFactory.decodeFile(path, o2);
Bitmap bitmap = bm;
ExifInterface exif = new ExifInterface(path);
orientation = exif
.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("ExifInteface .........", "rotation =" + orientation);
// exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
// m.postScale((float) bm.getWidth(), (float) bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
return bitmap;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
return bitmap;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), m, true);
return bitmap;
}
return bitmap;
} catch (Exception e) {
return null;
}
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
private void doCrop() {
final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = getPackageManager().queryIntentActivities(
intent, 0);
int size = list.size();
if (size == 0) {
Toast.makeText(this, "Can not find image crop app",
Toast.LENGTH_SHORT).show();
return;
} else {
intent.setData(mImageCaptureUri);
intent.setClassName("com.android.camera",
"com.android.camera.CropImage");
intent.putExtra("outputX", 100);
intent.putExtra("outputY", 100);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
intent.putExtra("return-data", true);
// startActivityForResult(intent, CROP_FROM_CAMERA);
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent(new ComponentName(res.activityInfo.packageName,
res.activityInfo.name));
startActivityForResult(i, CROP_FROM_CAMERA);
} else {
for (ResolveInfo res : list) {
final CropOption co = new CropOption();
co.title = getPackageManager().getApplicationLabel(
res.activityInfo.applicationInfo);
co.icon = getPackageManager().getApplicationIcon(
res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent
.setComponent(new ComponentName(
res.activityInfo.packageName,
res.activityInfo.name));
cropOptions.add(co);
}
CropOptionAdapter adapter = new CropOptionAdapter(
getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Crop App");
builder.setAdapter(adapter,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
startActivityForResult(
cropOptions.get(item).appIntent,
CROP_FROM_CAMERA);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
if (mImageCaptureUri != null) {
getContentResolver().delete(mImageCaptureUri, null,
null);
mImageCaptureUri = null;
}
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
}