As in the below code, I am capturing Images, cropping it and using them. On cropping the images, the image is badly distorted and having no quality.Please help me.
public class ScanActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
captureImage();
}
private void captureImage() {
try {
//Capture the image from rear Camera
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Crop the captured image
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", 0);
cameraIntent.putExtra("aspectY", 0);
cameraIntent.putExtra("outputX", 200);
cameraIntent.putExtra("outputY", 200);
startActivityForResult(cameraIntent, CAMERA_CAPTURE);
} catch (Exception e) {
Toast.makeText(ScanActivity.this, errorMessage, Toast.LENGTH_SHORT).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_OK || requestCode != CAMERA_CAPTURE)
return;
if (requestCode == CAMERA_CAPTURE) {
Bundle extras = data.getExtras();
if (extras != null) {
if (data != null) {
Bitmap bitmap = extras.getParcelable("data");
imageView.setImageBitmap(bitmap);
// convert bitmap to JPEG to save as a byte[]
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// compress the image
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
// convert to byte array
final byte[] imageInByte = stream.toByteArray();
}
I tried the below code but it doesnt seem to be of any help:
int newWidth=200;
int newHeight=200;
Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
float ratioX = newWidth / (float) bitmap.getWidth();
float ratioY = newHeight / (float) bitmap.getHeight();
float middleX = newWidth / 2.0f;
float middleY = newHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bitmap, middleX - bitmap.getWidth() / 2, middleY - bitmap.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
imageView.setImageBitmap(scaledBitmap);
Related
I have the camera up and running, and saving the picture to my phone, but I now want to display it in an ImageView that I have set up, and then once more every time the app is launched after that. Any suggestions on how I can expand upon what I already have to achieve this?
My camera code is as follows:
private void takePic() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureName = "Avatar.jpg";
File imageFile = new File(pictureDirectory, pictureName);
Uri pictureUri = Uri.fromFile(imageFile);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
And I have a button that simply calls on takePic(). I had an onActivityResult() before that looked like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
AvatarMe.setImageBitmap(photo);
}
}
I used this to simply display the thumbnail in my ImageView, but when I modified the code to save the picture I had to remove it, otherwise the app would crash. It seems Android won't let me do both, so I need some help to figure out how I can do that.
So basically I want to take a picture, display it in my ImageView, and save it so that if the app is killed after the picture has been taken I can just fill the ImageView with the saved picture.
You can do it with picasso library.
In your onActivityResult() data is coming from intent but you have to save into internal storage and show in imageview, have look.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
{
if (resultCode == Activity.RESULT_OK)
{
Bitmap bmp = (Bitmap)data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//saving image into internal storage
File myfile = new File(Environment.getExternalStorageDirectory(),"yourfilename.jpg");
FileOutputStream fo;
try {
myfile.createNewFile();
fo = new FileOutputStream(myfile);
fo.write(byteArray);
fo.flush();
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// convert byte array to Bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
byteArray.length);
imageView.setImageBitmap(bitmap);
}
}
}
Happy coding!!
you can use picasso library or you can my approach that i use that compress tha image and this ImageCompression class
`
private Context context;
float maxHeight;
float maxWidth;
boolean wantSave;
public ImageCompression(Context context) {
this.context = context;
}
public ImageCompression(Context context, float maxHeight, float maxWidth, boolean wantSave) {
this.context = context;
this.maxHeight = maxHeight;
this.maxWidth = maxWidth;
this.wantSave = wantSave;
}
#Override
protected Bitmap doInBackground(String... strings) {
if (strings.length == 0 || strings[0] == null)
return null;
return compressImage(strings[0]);
}
protected void onPostExecute(Bitmap imagePath) {
// imagePath is path of new compressed image.
}
public Bitmap compressImage(String imagePath) {
// to check if image is exist or not
File checkFile = new File(imagePath);
if (!checkFile.exists()) {
return null;
}
Bitmap scaledBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap bmp = BitmapFactory.decodeFile(imagePath, options);
int actualHeight = options.outHeight;
int actualWidth = options.outWidth;
float imgRatio = (float) actualWidth / (float) actualHeight;
float maxRatio = maxWidth / maxHeight;
if (actualHeight > maxHeight || actualWidth > maxWidth) {
if (imgRatio < maxRatio) {
imgRatio = maxHeight / actualHeight;
actualWidth = (int) (imgRatio * actualWidth);
actualHeight = (int) maxHeight;
} else if (imgRatio > maxRatio) {
imgRatio = maxWidth / actualWidth;
actualHeight = (int) (imgRatio * actualHeight);
actualWidth = (int) maxWidth;
} else {
actualHeight = (int) maxHeight;
actualWidth = (int) maxWidth;
}
}
options.inSampleSize = calculateInSampleSize(options, actualWidth, actualHeight);
options.inJustDecodeBounds = false;
options.inDither = false;
options.inPurgeable = true;
options.inInputShareable = true;
options.inTempStorage = new byte[16 * 1024];
try {
bmp = BitmapFactory.decodeFile(imagePath, options);
scaledBitmap = Bitmap.createBitmap(actualWidth, actualHeight, Bitmap.Config.RGB_565);
float ratioX = actualWidth / (float) options.outWidth;
float ratioY = actualHeight / (float) options.outHeight;
float middleX = actualWidth / 2.0f;
float middleY = actualHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
if (bmp != null) {
canvas.drawBitmap(bmp, middleX - bmp.getWidth() / 2, middleY - bmp.getHeight() / 2, new Paint(Paint.FILTER_BITMAP_FLAG));
bmp.recycle();
}
ExifInterface exif;
try {
exif = new ExifInterface(imagePath);
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
Matrix matrix = new Matrix();
if (orientation == 6) {
matrix.postRotate(90);
} else if (orientation == 3) {
matrix.postRotate(180);
} else if (orientation == 8) {
matrix.postRotate(270);
}
scaledBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(), scaledBitmap.getHeight(), matrix, true);
} catch (IOException e) {
e.printStackTrace();
}
// these lines from 144 to 157 for save the new photo
if (wantSave) {
FileOutputStream out = null;
String filepath = imagePath;
try {
out = new FileOutputStream(filepath);
//write the compressed bitmap at the destination specified by filename.
scaledBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return scaledBitmap;
} catch (OutOfMemoryError exception) {
exception.printStackTrace();
}
return null;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
final float totalPixels = width * height;
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
return inSampleSize;
}
}
then in onActivityResult call
ImageCompression imageCompression = new ImageCompression(context, imageHeight, imageHeight, false) {
#Override
protected void onPostExecute(Bitmap bitmab) {
super.onPostExecute(bitmab);
try {
if (imagePath != null) {
mCropImageView.setImageBitmap(bitmab);
}
} catch (OutOfMemoryError error) {
Toast.makeText(CropImageActivity.this, "OutOfMemory, no space", Toast.LENGTH_SHORT).show();
}
}
};
imageCompression.execute(imagePath);
i hope this will help
The "data" from the camera intent is null in this case. You can check this answer.
To solve this problem, you will have to make the uri you passed to the camera intent global.
//make this a global variable
Uri pictureUri = Uri.fromFile(imageFile);
then you can access the bitmap like this
void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK)
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), pictureUri);
AvatarMe.setImageBitmap(bitmap);
}
}
You can also store the pictureUri using a db or shared preference and reuse it later.
I want to crop face from image . I have an imageview .
iv1 = (ImageView) MainActivity.this.findViewById(R.id.img1);
When I click this imageview it pick one image from Gallery . The code is as below :
iv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
imgNo = 1;
}
});
In onActivityResult method I have added the code for cropping face from choosen image . The code is as below :
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode)
{
case SELECT_PHOTO:
if (resultCode == RESULT_OK && imgNo == 1 )
{
selectedImage = imageReturnedIntent.getData();
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
yourSelectedImage = BitmapFactory.decodeStream(imageStream);
iv1.setImageBitmap(yourSelectedImage);
path1 = selectedImage.getPath();
bmpimg1 = yourSelectedImage;
viewHeight = iv1.getMeasuredHeight();
viewWidth = iv1.getMeasuredWidth();
try {
Paint paint = new Paint();
paint.setFilterBitmap(true);
Bitmap bitmapOrg =yourSelectedImage;
int targetWidth = bitmapOrg.getWidth();
int targetHeight = bitmapOrg.getHeight();
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight, Bitmap.Config.ARGB_8888);
RectF rectf = new RectF(0, 0, viewWidth, viewHeight);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addRect(rectf, Path.Direction.CW);
canvas.clipPath(path);
canvas.drawBitmap(
bitmapOrg,
new Rect(0, 0, bitmapOrg.getWidth(), bitmapOrg
.getHeight()), new Rect(0, 0, targetWidth,
targetHeight), paint);
Matrix matrix = new Matrix();
matrix.postScale(1f, 1f);
BitmapFactory.Options bitmapFatoryOptions = new BitmapFactory.Options();
bitmapFatoryOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOrg = yourSelectedImage;
myFace = new FaceDetector.Face[5];
myFaceDetect = new FaceDetector(targetWidth, targetHeight,
5);
int numberOfFaceDetected = myFaceDetect.findFaces(
bitmapOrg, myFace);
Bitmap resizedBitmap = null;
if (numberOfFaceDetected > 0) {
PointF myMidPoint = null;
android.media.FaceDetector.Face face = myFace[0];
myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance() + 20;
if (myMidPoint.x + viewWidth > targetWidth) {
while (myMidPoint.x + viewWidth > targetWidth) {
myMidPoint.x--;
}
}
if (myMidPoint.y + viewHeight > targetHeight) {
while (myMidPoint.y + viewHeight > targetHeight) {
myMidPoint.y--;
}
}
resizedBitmap = Bitmap.createBitmap(bitmapOrg,
(int) (myMidPoint.x - myEyesDistance),
(int) (myMidPoint.y - myEyesDistance),
viewWidth, viewHeight, matrix, true);
} else {
resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
viewWidth, viewHeight, matrix, true);
}
/* convert Bitmap to resource */
// Bitmap resizedBitmap = Bitmap.createBitmap(targetBitmap,
// 0,
// 0, viewWidth, viewHeight, matrix, true);
BitmapDrawable bd = new BitmapDrawable(resizedBitmap);
iv1.setBackgroundDrawable(new BitmapDrawable(
getCroppedBitmap(bd.getBitmap())));
} catch (Exception e) {
System.out.println("Error1 : " + e.getMessage()
+ e.toString());
}
iv1.invalidate();
}
else if (resultCode == RESULT_OK && imgNo == 2)
{
Bitmap photo = (Bitmap) imageReturnedIntent.getExtras().get("data");
iv2.setImageBitmap(photo);
// path2 = imageReturnedIntent.getData().getPath();
bmpimg2 = photo;
iv2.invalidate();
}
}
}
But the image is not cropping . How can I crop face from image ? Any advice is of great help .
To crop faces automatically, you have to instantiate an object of FaceCropper class in that way:
AndroidFaceCropper library download from github
https://github.com/lafosca/AndroidFaceCropper
You can use this library for croping faces from images.
This will produce result like this.
You can also select face type like.
Final result.
I'm working in an app that take an image from the gallery and save it into parse.
The problem is that when I pick an image taken by the camera the size of the image is too big and takes some seconds to load the image in an image view. Also when I save the image and download again in the app it takes a lot of time because it has to download a big image.
I don't know how I reduce the size of the image picked. I tried several things but anything works.
This is my code at this moment
public class Datos extends Activity implements OnItemSelectedListener {
private final int SELECT_PHOTO = 1;
private ImageButton imageView;
ParseFile file;
byte [] data;
/*
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_datos);
btnClick();
imageView = (ImageButton) findViewById(R.id.imageButton);
ImageButton pickImage = (ImageButton) findViewById(R.id.imageButton);
pickImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
//photoPickerIntent.putExtra("outputX", 150);
//photoPickerIntent.putExtra("outputY", 100);
//photoPickerIntent.putExtra("aspectX", 1);
//photoPickerIntent.putExtra("aspectY", 1);
//photoPickerIntent.putExtra("scale", true);
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
try {
Uri imageUri = imageReturnedIntent.getData();
InputStream imageStream = getContentResolver().openInputStream(imageUri);
Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
imageView.setImageBitmap(selectedImage);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
selectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
data = stream.toByteArray();
BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), selectedImage);
imageView.setBackgroundDrawable(bitmapDrawable);
BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
Bitmap bmp = drawable.getBitmap();
Bitmap b = Bitmap.createScaledBitmap(bmp, 120, 120, false);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
Spinner spinner = (Spinner) parent;
if (spinner.getId() == R.id.telefono) {
consola = parent.getItemAtPosition(position).toString();
} else if (spinner.getId() == R.id.provincia) {
provincia = parent.getItemAtPosition(position).toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
public void btnClick() {
Button buttonEnviar = (Button) findViewById(R.id.enviar);
buttonEnviar.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//Storing image in parse passed in onclick method of a button with the below code:
Intent intentDatos = new Intent(Datos.this, Inicio.class);
startActivity(intentDatos);
ParseObject testObject = new ParseObject("Musica");
if (data != null) {
file = new ParseFile("selected.png", data);
}
else {
data = "".getBytes();
file = new ParseFile("selected.png", data);
}
//file.saveInBackground();
testObject.put("imagen", file);
testObject.saveInBackground();
}
});
}
Does Anyone know how to do it?
Thanks for your help,
This answer will help you
if you want bitmap ratio same and reduce bitmap size. then pass your
maximum size bitmap. you can use this function
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float)width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
change your onActivityResult in SELECT_PHOTO case like this:
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
try {
Uri imageUri = imageReturnedIntent.getData();
InputStream imageStream = getContentResolver().openInputStream(imageUri);
Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
selectedImage = getResizedBitmap(selectedImage, 400);// 400 is for example, replace with desired size
imageView.setImageBitmap(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
When I pick an image from the gallery it is too large and I need to resize it. Can anyone give me suggestions on how I might be able to accomplish this?
See code below:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = Media.getBitmap(this.getContentResolver(), uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
imageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_GALLERY);
imageView.setImageBitmap(bitmap);
}
});
This post has some excellent samples for you: How to Resize a Bitmap in Android?
In your case, this method helps
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
Edit
Also from the same post, this fits your need in an easier way
Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, false);
Update
You can use the code in this way:
// Set the new width and height you want
int newWidth;
int newHeight;
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = Media.getBitmap(this.getContentResolver(), uri);
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The first file allow the user to pick a photo from the gallery and sends it to an activity which will process it. The problem is that the image is too large for the phone's screen, so you only see the top corner of the image(as if it has been magnified).
Button useGallery = (Button)findViewById(R.id.loadfromgallery);
useGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}}) ;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
Intent intent = new Intent(mContext, DisplayUndistortedBitmapFromGalleryActivity.class);
intent.setData(selectedImage);
startActivity(intent);
if(yourSelectedImage != null){
Log.e(TAG,"pic ok");
}else{
Log.e(TAG,"pic not ok");
}
}
}
. The 2nd file is the activity that recieves the image data from the intent and places it in a URI that a bitmap is the derived from.
public class DisplayUndistortedBitmapFromGalleryActivity extends Activity {
private static final String TAG = "*********DUBFGActivity";
private Context mContext = this;
Uri uri;
private Bitmap mbitmap = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
uri = getIntent().getData();
if(uri != null){
Log.e(TAG, "uri ok");
}else {
Log.e(TAG, "uri not ok");
}
try {
mbitmap = Media.getBitmap(getContentResolver(), uri);
//setMbitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
.
I have a 3rd file which is the customview for the activity. The line below retrieves the bitmap from it's activity and displays it. Is there a way of downsizing the bitmap so it fits on the screen? thanks.
Bitmap bm = ((DisplayUndistortedBitmapFromGalleryActivity)getContext()).getMbitmap();
Here is how i usually resize a bitmap and is the easiest way.
public class bitmaptest extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout linLayout = new LinearLayout(this);
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
BitmapDrawable bmd = new BitmapDrawable
EDIT:
Here is another option.
int targetWidth = bitmapOrg.getWidth() - 15; //change this to control the size
int targetHeight = bitmapOrg.getHeight() - 15 ;
Matrix matrix = new Matrix();
matrix.postScale(1f, 1f);
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, targetWidth, targetHeight, matrix, true);