low quality when capture picture and send it image view - android

low quality when capture picture and send it image view
when imgCamera button pressed
case R.id.imgCamera:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
break;
**the activity result :**
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CAMERA_REQUEST:
mPhotoEditor.clearAllViews();
Bitmap photo = (Bitmap) data.getExtras().get("data");
mPhotoEditorView.getSource().setImageBitmap(photo);
break;
case PICK_REQUEST:
try {
mPhotoEditor.clearAllViews();
Uri uri = data.getData();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
mPhotoEditorView.getSource().setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
please help me I want to get the best quality for the picture captured

To save the full-size image you need to do much more stuff.
data.getData();
This would return image thumbnail which is a low-quality image for the original one.
I can't find an accurate guide than the official documentation. check this link from Android Developer documentation. Following it, you would save the high-quality image easily instead of a low-quality one. Not to mention, You would learn about FileProivder and storage (Maybe you like to save it internal storage or external storage).
Be patient .. happy coding

my comment tells you want is wrong. Here's the solution:
first, modify your camera intent:
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
_photoUri = createImageUri();
// Continue only if the File was successfully created
if (_photoUri != null) {
//setflags is required to clear flag_activity_new_task that is automatically set on
//direct calls. If not cleared, you get instant returns from the app.
takePictureIntent.setFlags(0);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, _photoUri);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
private Uri createImageUri() {
return FileProvider.getUriForFile(this
, this.getApplicationContext().getPackageName()
, new File(Environment.getExternalStorageDirectory()
, "orderphoto.jpg"));
}
this tells the camera where to put the photo.
check in your activity result for RESULT_OK to ensure they didn't cancel.
You'll need to then be able to read from the file system. Here's how our app does it: Note i can't be positive i'm not referencing a custom function in this. YMMV.
private Bitmap DecodeFile(Uri fileUri) {
/* There isn't enough memory to open up more than a couple camera photos */
/* So pre-scale the target _bitmap into which the file is decoded */
/* Get the size of the ImageView */
int targetW = _imageView.getWidth();
int targetH = _imageView.getHeight();
/* Get the size of the image */
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(fileUri.getPath(), bmOptions);
// TODO: 2/25/2019 Update to BitmapFactory.decodeStream()
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
if (photoW == 0 || photoH == 0) {
AppUtility.ShowToast("BitmapFactory.Decode: File Decoding Failed!");
}
/* Figure out which way needs to be reduced less */
int scaleFactor = 1;
if ((targetW > 0) || (targetH > 0)) {
scaleFactor = Math.min(photoW/targetW, photoH/targetH);
}
/* Set _bitmap options to scale the image decode target */
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
/* compress/shrink the bitmap */
// TODO: 2/25/2019 Update to BitmapFactory.decodeStream()
return BitmapFactory.decodeFile(fileUri.getPath(), bmOptions);
}
When you use this, it does all the hard work for you and sizes it to the screen. Note that some samsung devices lie about the orientation so you may have problems about that.

Related

Image from path wont load

I got this listener:
#Override
public void onClick(View v) {
showDialog();
ImageButton currentButton = (ImageButton)v;
Bitmap bmp = BitmapFactory.decodeFile(mCurrentPhotoPath);
currentButton.setImageBitmap(bmp);
}
Image is successfully taken in showDialog() but after this it wont set to imageButton. It goes white. The path generated is:
file:/storage........../filename.jpg amd its saved in mCurrentPhotoPath
I tried setting image from drawable after shot is made just to try it and it works. For some reason i cant set the image to the ImageButton.Do i have to resize it(photo is made full sized)?
Following THIS tutorial i did this:
#Override
public void onClick(View v) {
showDialog((ImageButton)v);
setPic((ImageButton)v);
}
private void setPic(ImageButton mImageView) {
if (shotFired){
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath,bmOptions);
mImageView.setImageBitmap(bitmap);
mImageView.setTag(mCurrentPhotoPath);
shotFired=false;
}
Seems if i calll setPic() without making a new shot and just call the old one ive made it works. Must be something in timing...I need to get this thing working.
If you are using camera for taking the picture to set it to ImageView, then you need to set the image in onActivityResult() after the image is captured using camera.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
//set the image to imageView
} else if (resultCode == Activity.RESULT_CANCELED) {
//image was not taken
//show some error message
}
}
i believe you problem is because of outOfMEmory problem that normaly happens when loading a bitmap into the memory.
the best practice to load bitmaps in android is to find the bitmap dimensions before you load it. then loading a suitable size of the bitmap depend on your device memory size and screen size.
i highly recommend you to read this great tutorial in develope.android website. this will help you to get a complete sens about how bitmaps works and whats the best practice to load them also source code is included. please go through all these tutorials.
https://developer.android.com/training/displaying-bitmaps/index.html
https://developer.android.com/training/displaying-bitmaps/load-bitmap.html
https://developer.android.com/training/displaying-bitmaps/process-bitmap.html
https://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
https://developer.android.com/training/displaying-bitmaps/manage-memory.html
https://developer.android.com/training/displaying-bitmaps/display-bitmap.html
i suggest you to read these links but if you nor intersted you can use libraries like Glide or Piccasso for loading your bitmap. they will help you to load without an OutOfMemoty Error.

Android cropped image quality issue

I am trying to save an image as cropped from android and then show it in my app. I am using the code below, but when I try to view the image in my app the image quality is not good as in the attached image. Am doing anything wrong? Any help would be great.
My code is:
dipToPixel = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 1, getResources().getDisplayMetrics());
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == getActivity().RESULT_OK && data != null) {
picUri = data.getData();
performCrop();
}
if (requestCode == 111 && resultCode == getActivity().RESULT_OK && data != null) {
Bundle extras = data.getExtras();
Bitmap bitmapImage = extras.getParcelable("data");
tweetImage.setImageBitmap(bitmapImage);
tweetImage.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
tweetImage.getViewTreeObserver().removeOnPreDrawListener(this);
widthPixel = tweetImage.getMeasuredWidth();
heightPixel = tweetImage.getMeasuredHeight();
return true;
}
});
System.out.println("photo added");
addPhotoVar = 1;
addPhotoBtn.setText("remove");
}
callbackManager.onActivityResult(requestCode, resultCode, data);
}
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(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", Math.round(screenWidth / dipToPixel)-10);
cropIntent.putExtra("outputY", Math.round(screenWidth / dipToPixel)-10);
//retrieve data on return
cropIntent.putExtra("return-data", true);
//start the activity - we handle returning in onActivityResult
startActivityForResult(cropIntent, 111);
}
// 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(getActivity(), errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
Below is the code that I use the image and save to database:
tweetImage.buildDrawingCache();
bm = tweetImage.getDrawingCache();
if (widthPixel < heightPixel) {
basePixel = widthPixel;
}
else {
basePixel = heightPixel;
}
if (basePixel > 768) {
widthRatio = (float) 768/basePixel;
heightRatio = (float) 768/basePixel;
}
else {
widthRatio = 1;
heightRatio = 1;
}
Bitmap bmResized = Bitmap.createScaledBitmap(bm,(int)(widthPixel*widthRatio), (int)(heightPixel*heightRatio), true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmResized.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byteArray1 = stream.toByteArray();
image1 = new ParseFile("profilePhoto.jpg", byteArray1, "image/jpg");
Use this library, this library manage cropped image quality as well it keeps both image Crop Library
Change :
bmResized.compress(Bitmap.CompressFormat.JPEG, 100, stream);
to :
bmResized.compress(Bitmap.CompressFormat.PNG, 100, stream);
Since JPEG format uses a lossy compression, you should use PNG to save the bitmap, if you don't want quality loss.
Also, you should avoid using com.android.camera.action.CROP intent as it doesn't exist on all the devices as explained here.
There are some alternatives listed on the above link, you may use one of them.
Please refer this link :
https://commonsware.com/blog/2013/01/23/no-android-does-not-have-crop-intent.html
Here are some libraries to consider for image crop:
https://github.com/lvillani/android-cropimage
https://github.com/biokys/cropimage
https://github.com/MMP-forTour/cropimage (forked from the above one)
https://github.com/dtitov/pickncrop

Taking Picture via intent to internal (app) storage returns null for bitmap

The scope: I want to take a picture via intent and save the picture to the internal storage of my app.
Then I want to load a scaled version into a byte array (from inputstream), save this scaled image as byte array into SQLight.
After saving it to the database I want to delete the picture.
(This question only is about saving the image to internal storage, the scope is only here because there is always someone that ask about it)
The problem: I'm stuck at saving the picture to the internal storage.
I'll add examples from my debugging session as comments behind the variables to show the values i got while testing.
I have an ImageView which has an onClickListener that starts the takePictureIntent:
With following global attributes:
Uri mCurrentPhotoUri; //URI to file
File mCurrentPicture; //the current picture don't know if I need it somewhere but for complete understanding of code
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent for the on-board camera
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//device has camera
if(takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
//create a file with path the code below
photoFile = createImageFile(); //sets photoFile to: /data/data/my.app.project/app_photo/JPEG_20151105_092219_-1434131481.jpg
} catch (IOException e) {
e.printStackTrace();
}
//file has been created, set members and add Extra to intent, then start intent.
if(photoFile != null) {
mCurrentPicture = photoFile; // well, same as above
mCurrentPhotoUri = Uri.fromFile(photoFile); // this looks somehow wrong, but I don't know much about URIs: file:///data/data/my.app.project/app_photo/JPEG_20151105_092219_-1434131481.jpg
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile)); //same URI as above that extra should be needed to tell the cam that I don't want to save to the default path but my app path
startActivityForResult(takePictureIntent, 10); //start the intent and use requestcode 10 for onActivityResult ...
}
}
}
});
The creation of the file path:
//code from google developers with some changes.
private File createImageFile() throws IOException {
String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); //from today value: 20151105_092219
String imageFilename = "JPEG_" + timestamp + "_"; // concat is this: JPEG_20151105_092219_
File storageDir = this.getDir("photo", MODE_PRIVATE); //String path is: /data/data/my.app.project/app_photo
storageDir.mkdirs();
File image = File.createTempFile(imageFilename, ".jpg", storageDir); //String path is: /data/data/my.app.project/app_photo/JPEG_20151105_092219_-1434131481.jpg
mCurrentPhotoPath = "file:" + image.getAbsolutePath(); //here I put the absolute path into static mCurrentPhotoPath, concate with the "file:" from googledeveloper guide: file:/data/data/my.app.project/app_photo/JPEG_20151105_092219_-1434131481.jpg
return image;
}
So the camera opens and I can take a picture and I'm ask if I want to save that picture (all from the build-in camera app, device is a samsung galaxy note).
Then my onActivityResult-Method is called:
I used data as parameter because I used the mini byte array for something, but with the custom storage this returns null and it isn't used anymore.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch(requestcode) {
...
case 10:
setImageView(ivPreview1, data, 0);
ivPreview.setVisibility(View.VISIBLE);
break;
...
}
...
}
}
Method setImageView:
private void setImageView(ImageView iv, Intent data, int index) {
try {
Uri u = mCurrentPhotoUri; //sets u to: file:///data/data/my.app.project/app_photo/JPEG_20151105_092219_-1434131481.jpg
File file = new File(u.getPath()); //sets file to: /data/data/my.app.project/app_photo/JPEG_20151105_092219_-1434131481.jpg
Bitmap bm = null;
ByteArrayOutputStream baos = null;
int orientation = 0;
if (file.exists()) { //this is true
//found that somewhere in the developer training:
ExifInterface exif = null;
try {
exif = new ExifInterface(photoUri.getPath());
} catch (IOException e) {
e.printStackTrace();
}
if(exif != null)
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0); //is 0 (i didn't rotate the tablet)
//resulution I want to resize the image to:
int reqWidth = 960, reqHeight = 1280;
//exchange values if orientation doesn't match landscape
if (orientation == 0 || orientation == 270) {
int temp = reqWidth;
reqWidth = reqHeight;
reqHeight = temp;
}
//this I used before I changed to internal storage to change the size of the image code below
bm = ImageManager.decodeSampledBitmapFromFile(u.getPath(), reqWidth, reqHeight); // returns null because of this everything following is null too.
if (orientation == 90 || orientation == 180 || orientation == 270) {
Matrix matrix = new Matrix();
// rotate the Bitmap
if (orientation == 90)
matrix.postRotate(90F);
else if (orientation == 270)
matrix.postRotate(-90F);
else
matrix.postRotate(180F);
// recreate the new Bitmap
bm = Bitmap.createBitmap(bm, 0, 0,
bm.getWidth(), bm.getHeight(), matrix, true);
}
baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, baos);
}
iv.setImageBitmap(bm);
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Could not take Photo: ", e);
}
}
The following methods that I used to decode the file (customisation of: http://developer.android.com/downloads/samples/DisplayingBitmaps.zip ):
The line with BitmapFactory.decodeFile(filename, options); also creates a log entry: D/skia: --- SkImageDecoder::Factory returned null
public static Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight) {
//this gets parameters:
// reqHeight: 960, reqWidth: 1280 and filename: /data/data/my.app.project/app_photo/JPEG_20151105_092219_-1434131481.jpg
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options); // this adds outHeight and outWidth to -1 (variables from options)
//this also creates a log entry: D/skia: --- SkImageDecoder::Factory returned null
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(filename, options);
return bmp;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// BEGIN_INCLUDE (calculate_sample_size)
// Raw height and width of image
final int height = options.outHeight; //is -1
final int width = options.outWidth; //is -1
int inSampleSize = 1;
//because its obviously smaller in both statements code will not be executed so it returns 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;
}
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger inSampleSize).
long totalPixels = width * height / inSampleSize;
// Anything more than 2x the requested pixels we'll sample down further
final long totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels > totalReqPixelsCap) {
inSampleSize *= 2;
totalPixels /= 2;
}
}
return inSampleSize;
// END_INCLUDE (calculate_sample_size)
}
I'm stuck at this for several days now I don't have any ideas that could solve my problem. This is also due to lack of android knowledge and the fact that i can't use emulators on my pc so i can't even look in the app folder to see if a picture was taken.
Try to get the path for storing temporary image like below.which will return your app folder location.and add the permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"photo";
Add uses-feature for camera access too.
<manifest ... >
<uses-feature android:name="android.hardware.camera"
android:required="true" />
Official documentation.

Xamarin.Forms Take photo with camera shows wrong orientation and crashes on back button

I am using the Xamarin.Forms Camera sample from here - https://github.com/XForms/Xamarin-Forms-Labs-Samples/tree/master/XF.Labs.CameraSample I am able to select or take a photo.
private async Task SelectPicture()
{
mediaPicker = DependencyService.Get<IMediaPicker>();
imageSource = null;
var mediaFile = await mediaPicker.SelectPhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
imageSource = ImageSource.FromStream(() => mediaFile.Source);
img.Source = imageSource;
}
private async Task TakePicture()
{
mediaPicker = DependencyService.Get<IMediaPicker>();
imageSource = null;
var mediaFile = await mediaPicker.TakePhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
imageSource = ImageSource.FromStream(() => mediaFile.Source);
img.Source = imageSource;
}
the code for the image is simply
img = new Image
{
BackgroundColor = Color.White,
Aspect = Aspect.AspectFit
};
There are a couple of issues:
First one. You can take a photo or select a stored one and it will then show it on the page. If you select a photo it displays it correctly, either portrait or landscape. When you take a photo, it only displays in landscape mode, so if the image was taken in portrait, the image shows on the side. This isn't catastrophic, but it would be better to show the image how it was taken.
The second issue is a bit more drastic, if you press the device's back button when you are either in the camera or the image gallery then the screen goes blank and then you get a message stating the app has stopped responding.
I have only tried this on Android so far. Does anyone have any ideas on how I can solve the above problems?
EDIT: I have managed to fix the crashing on back button, but the image still displays on its side for Android, but displays correctly for iOS
I would venture to guess there are a couple of issues here. One the Xamarin.Forms.Labs dependency injection handler on Android is 1) not checking for needed rotation, 2) is not checking for either external storage or is not handling onActivityCancelled.
The easy solution to your problem would be to use the Xamarin.Mobile Xamarin.Mobile I cannot 100% confirm it will handle everything but if it does this would be a quick and easy solution.
The more difficult option that will give you more control would be to roll your own platform specific implementation. I am not going to go into how DI works either you know or can see the Accessing Native Features
Here is an example of Android take picture with code for figuring out if the storage is external and whether or not rotation is needed.
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
//FinishActivity(requestCode);
try
{
if (resultCode == Result.Ok)
{
switch (requestCode)
{
case TAKE_PHOTO:
{
Java.IO.File photo = null;
if (isMounted)
{
photo = new Java.IO.File(Android.OS.Environment.ExternalStorageDirectory.ToString(), SharedLibrary.strPhotoLocation);
}
else
{
photo = new Java.IO.File(CacheDir, SharedLibrary.strPhotoLocation);
}
BitmapFactory.Options options = new BitmapFactory.Options();
options.InJustDecodeBounds = true;
options.InSampleSize = 4;
options.InPurgeable = true;
options.InInputShareable = true;
try
{
//Cleanup code... removed this in favor of using options.InJustDecodeBounds to get info about the bitmap
//instead of creating it twice in memory
//Bitmap imageBitmap = BitmapFactory.DecodeFile(photo.AbsolutePath, options);
//int w = imageBitmap.Width;
//int h = imageBitmap.Height;
BitmapFactory.DecodeFile(photo.AbsolutePath, options);
int w = options.OutWidth;
int h = options.OutHeight;
Matrix matrix = new Matrix();
matrix.SetRotate(getNeededRotation(photo.AbsolutePath));
options.InJustDecodeBounds = false;
//Bitmap imageBitmap = Bitmap.CreateBitmap(BitmapFactory.DecodeFile(photo.AbsolutePath, options), 0, 0, w, h, matrix, false);
Bitmap imageBitmap = Bitmap.CreateScaledBitmap(BitmapFactory.DecodeFile(photo.AbsolutePath, options), w, h, false);
//...
Get Mounted
private System.Boolean isMounted
{
get
{
return (System.Boolean)Android.OS.Environment.ExternalStorageState.Equals(Android.OS.Environment.MediaMounted);
}
}
GetRotationNeeded
private int getNeededRotation(string filepath)
{
ExifInterface exif = new ExifInterface(filepath);
int orientation = exif.GetAttributeInt(ExifInterface.TagOrientation, -1);
int rotate = 0;
switch (orientation)
{
case 6:
{
rotate = 90;
break;
}
case 3:
{
rotate = 180;
break;
}
case 8:
{
rotate = 270;
break;
}
default:
{
rotate = 0;
break;
}
}
exif.Dispose();
return rotate;
}
you can check orientation by using 'mediaFile.Exif.Orientation' to check whether it's portrait or Landscape.(' TopLeft'--> Portrait.) And then set photo orientation before saving using,
mediaFile.Exif.Orientation = ExifLib.ExifOrientation.TopLeft;

Memory/Allocation errors when setting ImageButton from Camera Photo

I am trying to take a photo from the phones camera and place in it in a ImageButton as part of a Profile activity including all users details, and then save the image as shared pref.
If I use the following code the ImageButton simply does not update:
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
// method checks data returned form camera via startActivityForResult
super.onActivityResult(requestCode, resultCode, data);
Runnable runnable = new Runnable(){#Override
public void run() {
handler.post(new Runnable(){
#Override
public void run() {
Bundle extras = data.getExtras();
photo = (Bitmap) extras.get("data");
takeAndSetPhoto.setImageBitmap(photo);
Toast.makeText(getBaseContext(), "Image set to profile!",
Toast.LENGTH_SHORT).show();
}//edn inner run
});//end new runnab;e
}
};
new Thread(runnable).start();
}//end if result OK
}// end onActivity
Alternatively the image DOES load if I use this method but I get erros:
Allocation fail for scaled Bitmap
Out Of Memory 01-03 10:13:06.645: E/AndroidRuntime(30163):
android.view.InflateException: Binary XML file line #18: Error
inflating class
The code is using Uro for phot taken:
public void run() {
Bundle extras = data.getExtras();
Uri photoShot = data.getData(); view
takeAndSetPhoto.setImageURI(photoShot);
Toast.makeText(getBaseContext(), "Image set to profile!",
Toast.LENGTH_SHORT).show();
}//edn inner run
All suggestions appreciated.
Cheers
Ciaran
Resizing Image:
When resizing the image:
Bitmap photoBitmap = Bitmap.createScaledBitmap(photo, 100, 100, false);
It works fine on the emulator with SD card activated, but crashes on a real device (a tablet 8inch)
Problem was I was not resizing image when taken form device phone, passed image to this method before setting to the image view:
public Bitmap reSizeImage(Bitmap bitmapImage) {
// resize bitmap image passed and rerun new one
Bitmap resizedImage = null;
float factorH = h / (float) bitmapImage.getHeight();
float factorW = w / (float) bitmapImage.getWidth();
float factorToUse = (factorH > factorW) ? factorW : factorH;
try {
resizedImage = Bitmap.createScaledBitmap(bitmapImage,
(int) (bitmapImage.getWidth() * factorToUse),
(int) (bitmapImage.getHeight() * factorToUse), false);
} catch (IllegalArgumentException e) {
Log.d(TAG, "Problem resizing Image #Line 510+");
e.printStackTrace();
}
Log.d(TAG,
"in resixed, value of resized image: "
+ resizedImage.toString());
return resizedImage;
}// end reSize

Categories

Resources