Android - resize/scale image through dragging and dropping - java

In Android, is there any built-in way for resizing an image through selecting it, and then dragging the corners/sides to the desired dimensions?
To illustrate what I wish to achieve:

I think what you are looking for is cropping image.
you can achieve that with default android Crop functionality:
private void performCrop(Uri picUri) {
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
// indicate image type and Uri
cropIntent.setDataAndType(picUri, "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", 128);
cropIntent.putExtra("outputY", 128);
// retrieve data on return
cropIntent.putExtra("return-data", true);
// start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, PIC_CROP);
}
// respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
// display an error message
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Constant declare:
final int PIC_CROP = 1;
override onActivity result method in your activity, writ following code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PIC_CROP) {
if (data != null) {
// get the returned data
Bundle extras = data.getExtras();
// get the cropped bitmap
Bitmap selectedBitmap = extras.getParcelable("data");
imgView.setImageBitmap(selectedBitmap);
}
}
}

Related

quallity of the image will be bad after cutting the image and sending it on the server?

I do not know , is the problem the cut function or the Decoding Code ? :
I use the code for for uploading:
public void Upload(View view) {
Bitmap Bimg = ((BitmapDrawable) image1.getDrawable()).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bimg.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
// Bimg.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream); // bad too
encodimg = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
and i use this code to cut the image :
private void performCrop(){
try {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 512);
cropIntent.putExtra("outputY", 512);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, PIC_CROP);
Toast toast = Toast.makeText(this, "Done", Toast.LENGTH_SHORT);
}
catch(ActivityNotFoundException anfe){
String errorMessage = "Soory - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
remark : I use a small image in xml as small preview :
<ImageView
android:onClick="Load_Picture"
android:id="#+id/imageview1"
android:background="#drawable/default_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
but i do not thing, the image size in xml is the problem
Iget the Bitmap from Camera or From Galerie like that :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ( requestCode==111 && resultCode==RESULT_OK ){
// Uri uri = data.getData();
// imageView.setImageURI(uri);
imageView.setImageBitmap((Bitmap)data.getExtras().get("data"));
}
}
the Problem is the cut methode , because if i upload the bitmap before cutting, i get very good quality. so the Problem is :
performCrop(){
You are not trying to send your cropped image to a server.
Instead you display the cropped image in an imageview. Then after that you take an screendump from that imageview and upload that to the server. Of course hat screendump has bad quality.
Instead you should upload the image you get from the crop function.
Please compare the resolution in pixels of all involved images.

Android. Crop images from Gallery

In my app i'm trying to crop images. I find some code that can crop images when a'm taking photo from camera, but i can't crop photos from gallery, cause:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=2, result=0, data=null} to activity {....MainActivity}: java.lang.NullPointerException "
in this line: Bundle extras = data.getExtras();
This is myActivity's code:
public class MainActivity extends Activity {
ImageView imVCature_pic;
Button btnCapture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeControls();
}
private void initializeControls() {
imVCature_pic=(ImageView)findViewById(R.id.imVCature_pic);
btnCapture=(Button)findViewById(R.id.btnCapture);
Button buttonGallery = (Button) findViewById(R.id.btn_select_gallery);
btnCapture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
/*create instance of File with name img.jpg*/
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "img.jpg");
/*put uri as extra in intent object*/
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
/*start activity for result pass intent as argument and request code */
startActivityForResult(intent, 1);
}
});
buttonGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent2 = new Intent();
intent2.setType("image/*");
intent2.setAction(Intent.ACTION_GET_CONTENT);
File file2 = new File(Environment.getExternalStorageDirectory() + File.separator + "img2.jpg");
/*put uri as extra in intent object*/
intent2.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file2));
/*start activity for result pass intent as argument and request code */
startActivityForResult(intent2, 3);
}} );
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//if request code is same we pass as argument in startActivityForResult
if(requestCode==1){
//create instance of File with same name we created before to get image from storage
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
//Crop the captured image using an other intent
try {
/*the user's device may not support cropping*/
cropCapturedImage(Uri.fromFile(file));
}
catch(ActivityNotFoundException aNFE){
//display an error message if user device doesn't support
String errorMessage = "Sorry - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
if(requestCode==2){
//Create an instance of bundle and get the returned data
Bundle extras = data.getExtras();
//get the cropped bitmap from extras
Bitmap thePic = extras.getParcelable("data");
//set image bitmap to image view
imVCature_pic.setImageBitmap(thePic);
}
if(requestCode==3){
//create instance of File with same name we created before to get image from storage
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "img.jpg");
//Crop the captured image using an other intent
try {
/*the user's device may not support cropping*/
cropCapturedImage(Uri.fromFile(file));
}
catch(ActivityNotFoundException aNFE){
//display an error message if user device doesn't support
String errorMessage = "Sorry - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
//create helping method cropCapturedImage(Uri picUri)
public void cropCapturedImage(Uri picUri){
//call the standard crop action intent
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri of image
cropIntent.setDataAndType(picUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 256);
cropIntent.putExtra("aspectY", 256);
//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, 2);
}
Where's a mistake?

Android camera to take multiple photos [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
The problem class:
public class problem extends Activity {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.problem);
iv=(ImageView) findViewById(R.id.imageView1);
Button b=(Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 0);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm=(Bitmap) data.getExtras().get("data");
iv.setImageBitmap(bm);
}
}
This is what I wanted to do:
Take multiple photos
show them in the screen
store them in the mysql databse.
I am new to android please tell me how to do that.I searched.But I could not find a answer.
From this code IT TAKE ONLY ONE PHOTO.
Show Image on Screen Before Saving :
Use my Code. I am taking a picture using camera intent and before saving it to gallery , it is showed to the user with a Save and Cancel Button :- Call Camera Intent :-
// This code is to call the camera intent. Basically it will start your camera. Put this code in a button or something
String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory() + File.separator +CommonFunction.getDateTime()+".jpg"; // Get File Path
Intent takePictureFromCameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
takePictureFromCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(SD_CARD_TEMP_DIR)));
startActivityForResult(takePictureFromCameraIntent, 123);
onActivityResult : -
// This function is called when you come back to your activity after the intent has finished. Do read android documentation on Google. It will Help
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_RESULT)
{
if (resultCode == Activity.RESULT_OK)
{
String galleryImatePath = SD_CARD_TEMP_DIR; // make SD_CARD_TEMP_DIR Global so that you can access it here from camera intent or pass it in put Extra method and retrieve it here
File f = new File(galleryImatePath);
try {//This code will rotate your image if you have taken the image by rotating the camera
Bitmap cameraBitmap = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inPurgeable = true;
bmOptions.inBitmap = cameraBitmap;
bmOptions.inMutable = true;
cameraBitmap = BitmapFactory.decodeFile(galleryImatePath,bmOptions);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
cameraBitmap.compress(Bitmap.CompressFormat.JPEG, 50, bos);
//To Rotate image Code
ExifInterface exif = new ExifInterface(galleryImatePath);
float rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
System.out.println(rotation);
float rotationInDegrees = exifToDegrees(rotation);
System.out.println(rotationInDegrees);
Matrix matrix = new Matrix();
matrix.postRotate(rotationInDegrees);
final Bitmap rotatedBitmap = Bitmap.createBitmap(cameraBitmap , 0, 0, cameraBitmap.getWidth(), cameraBitmap.getHeight(), matrix, true);
FileOutputStream fos=new FileOutputStream(galleryImatePath);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);
fos.write(bos.toByteArray());
cameraBitmap.recycle();
System.gc();
fos.flush();
fos.close();
// To set image in imageview in dialog. This code will set your image in a custon dialog box "captiondialog". It will contain a full width and height imageview and two textviews - done and cancel. It is upto u what you want to define in the textview's click listener. For example, you can pass the storing image in database in the "Done" textview and "Cancel" textview will dismiss your captiondialog and you app will return to your activity
Capdialog = new Dialog(AddToDo.this,android.R.style.Theme_NoTitleBar_Fullscreen);
Capdialog.setContentView(R.layout.captiondialog);
Capdialog.setCancelable(false);
TextView cancel = (TextView) Capdialog
.findViewById(R.id.cancel);
TextView done = (TextView) Capdialog.findViewById(R.id.done);
Capdialog.getWindow().setSoftInputMode (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
ImageView img = (ImageView) Capdialog.findViewById(R.id.image);
img.setImageBitmap(rotatedBitmap);
}
catch(Exception e){}
}
}
}
implement your done and cancel on click listener - what you want to do in them. My code will capture your image, rotate it in the right direction irrespective of camera rotation and show it to you in a dialog before saving it
This code will store your image in DB.You have to use "blob" to store image.. Use This Code :-
public void insertImageInDb(int id , Bitmap img ) {
byte[] data = bos.toByteArray(); // Use This or the code in comments below
/* ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, outputStream);
byte[] data = outputStream.toByteArray();*/
insertStatement_logo.bindLong(1, id);
insertStatement_logo.bindBlob(2, data);
insertStatement_logo.executeInsert();
insertStatement_logo.clearBindings() ;
}
There's an alternative intent action for the device camera that launches the camera in still image mode and does not exit until the user is finished with the activity:
Intent intent = new Intent(
MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
this.startActivity(intent);
Used with a ContentObserver this was exactly what I needed to accomplish. or Handle this in ActivityResult.
Note :- if you are new to android, this is too hard for you to understand now. Please read the android documentation first on google and read tutorials. Make basic apps. Learn first

Android image cropping is reducing the size of the image

I need to crop a photo from the android phone gallery and then edit it.
The original size of the photo is 3264 *2448 which is displayed in my screen of size 1280 * 720 as a scaled down image.
When I crop it, i am getting a image of size 185 * 139.
The code I am using for cropping is
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(picUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, PIC_CROP);
When I display the cropped image in an imageView it is displayed as a much smaller image.
I should be cropping the original sized image and not the scaled down version. Could any of you please guide me as to how to do this?
Please try this, i know its too late, but may help someone.
private void performCrop() {
try {
//call the standard crop action intent (the user device may not support it)
Intent cropIntent = new Intent("com.android.camera.action.CROP");
//indicate image type and Uri
cropIntent.setDataAndType(mImageCaptureUri, "image/*");
//set crop properties
cropIntent.putExtra("crop", "true");
//indicate aspect of desired crop
cropIntent.putExtra("aspectX", 4);
cropIntent.putExtra("aspectY", 3);
//indicate output X and Y
cropIntent.putExtra("outputX", 800);
cropIntent.putExtra("outputY", 800);
File f = new File(Environment.getExternalStorageDirectory(),
"/temporary_holder.jpg");
try {
f.createNewFile();
} catch (IOException ex) {
Log.e("io", ex.getMessage());
}
uri = Uri.fromFile(f);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(cropIntent, PIC_CROP);
} //respond to users whose devices do not support the crop action
catch (ActivityNotFoundException anfe) {
//display an error message
String errorMessage = "Your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Make your onActivityResult like this :-
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PIC_CROP) {
String filePath = Environment.getExternalStorageDirectory()
+ "/temporary_holder.jpg";
thumbnail = BitmapFactory.decodeFile(filePath);
//thumbnail = BitmapFactory.decodeFile(filePath);
// Log.i("",String.valueOf(thumbnail.getHeight()));
ImageView image = (ImageView) findViewById(R.id.pestImage);
image.setImageBitmap(thumbnail);
}
}
Add:
intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
Then you can get an image file which is not reduced. And use this saved file instead of:
Intent.getExtras().getParcelable("data")
Just ignore returned bitmap.
First off you should be aware that the crop intent cannot be relied upon for cross-device compatibility. (Any OEM can replace the stock camera/gallery app with their own version). This aside, I think you are missing a few extras that should go in the intent and give you your desired effect.
// width & height are your desired width/height for the cropped result
cropIntent.putExtra("outputX", width);
cropIntent.putExtra("outputY", height);
cropIntent.putExtra("aspectX", width);
cropIntent.putExtra("aspectY", height);
cropIntent.putExtra("scaleUpIfNeeded", true);
Try adding those to your intent and see how it turns out.

Building a Camera App - Receive

I am new to Android programming and I'm writing an application in Java that opens the camera take a photo and save it. I made it via Intents but I can't see onActivityResult running.
I have tested it into my phone (Samsung Galaxy S) and when I take the photo I receive a preview of that photo having two buttons one Save and the other Cancel. I haven't added something to my code to do this so I think it's something that camera does. I want after capturing the image to run onActivityResult (after I press the Save button on the preview).
But how I'm going to return a result to start onActivityResult after pressing the Button Save on the preview?
I FORGOT to tell that after i press save my entire app is terminated.
Here is my Code
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TakePicButton = (Button) findViewById(R.id.TakePicture);
TakePicButton.setOnClickListener((android.view.View.OnClickListener) this);
}
#Override
public void onDestroy(){
super.onDestroy();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
} else {
Toast.makeText(this, "Picture was not taken", Toast.LENGTH_SHORT);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.TakePicture){
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
}
try the below code, you will have to modify it a bit, it will help you get From Library and From Camera both, the SELECT_PICTURE is used for getting image from library
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case SELECT_PICTURE:
Uri selectedImageUri = data.getData();
filemanagerstring = selectedImageUri.getPath();
selectedImagePath = getPath(selectedImageUri);
if (selectedImagePath != null)
myFile = new File(selectedImagePath);
else if (filemanagerstring != null)
myFile = new File(filemanagerstring);
if (myFile != null) {
Bitmap bmp_fromGallery = decodeImageFile(selectedImagePath);
break;
case CAMERA_REQUEST:
Bitmap bmp_Camera = (Bitmap) data.getExtras().get("data");
break;
default:
break;
}
}

Categories

Resources