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();
}
}
}
}
Related
This question already has answers here:
How to use "Share image using" sharing Intent to share images in android?
(17 answers)
Closed 2 years ago.
I am making QR code generator
So far I made a generator button and save button.
It works fine.
I am trying to work on the sharing button.
It takes a few days to figure out as a beginner and still I cannot make it work.
At this code, if I click share, then the app closes.
/**Barcode share*/
findViewById(R.id.share_barcode).setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
});
I guessed the problem was path.
I use savepath to save qr code image. And then maybe it conflicts with String path
So I tried String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";;
It's not working. So maybe it's different problem and I don't know how to fix it.
Could you show me how to fix?
MainActivity
public class MainActivity extends AppCompatActivity {
private String inputValue;
private String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
private Bitmap bitmap;
private QRGEncoder qrgEncoder;
private ImageView qrImage;
private EditText edtValue;
private AppCompatActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qrImage = findViewById(R.id.qr_image);
edtValue = findViewById(R.id.edt_value);
activity = this;
/**Barcode Generator*/
findViewById(R.id.generate_barcode).setOnClickListener(view -> {
inputValue = edtValue.getText().toString().trim();
if (inputValue.length() > 0) {
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
qrgEncoder = new QRGEncoder(
inputValue, null,
QRGContents.Type.TEXT,
smallerDimension);
qrgEncoder.setColorBlack(Color.BLACK);
qrgEncoder.setColorWhite(Color.WHITE);
try {
bitmap = qrgEncoder.getBitmap();
qrImage.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else {
edtValue.setError(getResources().getString(R.string.value_required));
}
});
/**Barcode save*/
findViewById(R.id.save_barcode).setOnClickListener(v -> {
String filename = edtValue.getText().toString().trim();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try {
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename + ".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Objects.requireNonNull(fos).close();
Toast toast= Toast.makeText(getApplicationContext(),
"Image Saved. Check your gallery.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
edtValue.setText(null);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
boolean save = new QRGSaver().save(savePath, filename, bitmap, QRGContents.ImageType.IMAGE_JPEG);
String result = save ? "Image Saved. Check your gallery." : "Image Not Saved";
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
edtValue.setText(null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
}
});
/**Barcode share*/
findViewById(R.id.share_barcode).setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
});
}
}
I think you can solve this by:
Saving the bitmap in a file.
Then sharing the URI of that file in the intent.
In the code below, I am saving the image at the app level directory, you can choose your own and the code is written in kotlin.
Note: If you are using an app-level directory for saving the image then you must use the file provide to get the URI else it may result in FileUriExposedException
try {
val file = File(getExternalFilesDir(null),System.currentTimeMillis().toString() + ".png")
file.createNewFile()
val b = imageView.drawable.toBitmap()
FileOutputStream(file).use { out ->
b.compress(Bitmap.CompressFormat.PNG, 100, out)
}
val share = Intent(Intent.ACTION_SEND)
share.type = "image/jpeg"
val photoURI = FileProvider.getUriForFile(this, applicationContext.packageName.toString() + ".provider", file)
share.putExtra(Intent.EXTRA_STREAM, photoURI)
startActivity(Intent.createChooser(share, "Share Image"))
Toast.makeText(this, "Completed!!", Toast.LENGTH_SHORT).show()
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
}
In JAVA:
public void shareImage(Activity activity, ImageView imageView) {
try {
File file = new File(activity.getExternalFilesDir(null), System.currentTimeMillis() + ".png");
file.createNewFile();
Bitmap bitmap = drawableToBitmap(imageView.getDrawable());
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
Intent share = new Intent("android.intent.action.SEND");
share.setType("image/jpeg");
Uri photoURI = FileProvider.getUriForFile(activity,activity.getPackageName(), file);
share.putExtra("android.intent.extra.STREAM", photoURI);
activity.startActivity(Intent.createChooser(share, "Share Image"));
} catch (Exception var14) {
}
}
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
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 am capturing an image and store it in storage in mobile but when I get this image it cannot show any thing in Image View. I have tried a lot of code to get images from file but none of them are working in my emulator or real Samsung device.
enter code here
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);
}
});
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);
}
}
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; */
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
// File imgFile = new File(filename);
//("/sdcard/Images/test_image.jpg");
Bitmap myBitmap;
if(imageFile.exists()){
myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
// ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
// myImage.setImageBitmap(myBitmap);
return myBitmap;
}
return null;
}
First of All make sure you have declared the "Access External Storage" and "Access Hardware Camera" permissions in "AndroidManifest" and if you are using Android version 23 or 23+ then you have to take permissions on run-time.
If this is not the problem then use this code given below, it's working fine for me.
For Camera:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, ACTION_REQUEST_CAMERA);
For Gallery:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Intent chooser = Intent.createChooser(intent, "Choose a Picture");
startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
OnActivityResultMethod:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ACTION_REQUEST_GALLERY:
Uri galleryImageUri = data.getData();
try{
Log.e("Image Path Gallery" , getPath(getActivity() , galleryImageUri));
selectedImagePath = getPath(getActivity() , galleryImageUri);
} catch (Exception ex){
ex.printStackTrace();
Log.e("Image Path Gallery" , galleryImageUri.getPath());
selectedImagePath = galleryImageUri.getPath();
}
break;
case ACTION_REQUEST_CAMERA:
// Uri cameraImageUri = initialURI;
Uri cameraImageUri = data.getData();
Log.e("Image Path Camera" , getPath(cameraImageUri));
selectedImagePath = getPath(cameraImageUri);
break;
}
}
}
Method to get path of Image returned from Camera:
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
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
I have an application with an image view, and when i click on it it opens menu of choosing Take From Gallery/ Open Camera.
after i choose a large image (large size or large scaling) the app crashes.
how can i fix it?
this is the code and logcat:
Select image+onActivityResult:
private void selectImage() {
final CharSequence[] options = { "Take Photo", "Choose From Gallery",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(
AddContactActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take Photo"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment
.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals("Choose From Gallery")) {
Intent intent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory()
.toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imginAdd.setImageBitmap(bitmap);
ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream3);
byteArray = stream3.toByteArray();
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System
.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage, filePath,
null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap bitmap = (BitmapFactory.decodeFile(picturePath));
Log.w("path of image from gallery......******************.........",
picturePath + "");
imginAdd.setImageBitmap(bitmap);
ByteArrayOutputStream stream4 = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream4);
byteArray = stream4.toByteArray();
}
}
}
Getting the image from another through sql:
(4 lines as one code, i have problem with quoting:)
Blockquote byte[] photo = rs.getBlob(rs
.getColumnIndex(DBHelper.CONTACTS_COLUMN_IMAGE));
ByteArrayInputStream imageStream = new ByteArrayInputStream(photo);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
imginView.setImageBitmap(theImage);
LOGCAT: http://textuploader.com/69on
Simply use this function which will decode your large image too.
private void setPic(final String path) {
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
final BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
bitmap = BitmapFactory.decodeFile(path, bmOptions);
}
Now call this function after retrieve your image path from gallery
setPic(imagepath);
imageView.setImageBitmap(bitmap); // this bitmap object will be declare globally