Hello I am having an issue when using the camera function in my android application. I am able to take a picture using the camera utility, however when returned back, the bitmap image is blank but formatted to the size of the picture taken. Am I missing something, to make the image show? Should I not be using imageview? Thanks! -T
private Uri capturedImageUri;
ImageView picture;
Button snapButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_observation);
picture = (ImageView) findViewById(R.id.imageView);
snapButton = (Button) findViewById(R.id.picButton);
snapButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
open();
}
});
}
public void open (){
File file = new File(Environment.getExternalStorageDirectory(), ("test"+".jpg"));
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else{
file.delete();
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
capturedImageUri = Uri.fromFile(file);
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(i, 2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
// super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
//Bitmap bitmap = (Bitmap) data.getExtras().get("data");
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), capturedImageUri);
picture.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
1) Call the camera intent
private void picPhoto() {
Intent pickIntent = new Intent();
if (Build.VERSION.SDK_INT < 19) {
pickIntent.setType("image/jpeg");
pickIntent.setAction(Intent.ACTION_GET_CONTENT);
} else {
pickIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
pickIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickIntent.setType("image/jpeg");
}
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, getFileDirectory());
takePhotoIntent.putExtra("android.intent.extras.CAMERA_FACING", 1);
String pickTitle = "Select or take a new Picture";
Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
chooserIntent.putExtra
(
Intent.EXTRA_INITIAL_INTENTS,
new Intent[]{takePhotoIntent}
);
startActivityForResult(chooserIntent, PICK_IMAGE);
}
2) Method getFileDirectory()
private Uri getFileDirectory() {
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs();
File image = new File(imagesFolder, "MY_PROFILE_PIC.jpg");
return Uri.fromFile(image);
}
3) OnActivityResult
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
// If gallary intent is choosed this condition remain true
if (requestCode == PICK_IMAGE && data != null && data.getData() != null) {
Uri _uri = data.getData();
//User had pick an image.
Cursor cursor = getActivity().getContentResolver().query(_uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
cursor.moveToFirst();
//Link to the image
final String imageFilePath = cursor.getString(0);
editPhoto1.setImageBitmap(null);
if (bmp != null) {
bmp.recycle();
}
setImagePicked(imageFilePath, 1);
cursor.close();
} else {
// If camera intent is choosed this condition remain true
editPhoto1.setImageBitmap(null);
if (bmp != null) {
bmp.recycle();
}
setImagePicked(getFileDirectory().getPath(), 0);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
3) Set the image
private void setImagePicked(String filePath, int status) {
try {
bmp = ImageResizer.decodeSampledBitmapFromFile(new File(filePath).getAbsolutePath(), 512, 342);
/* This for rotating the image use if necessary */
if (status == 0) {
Matrix mMatrix = new Matrix();
Matrix mat = editPhoto1.getImageMatrix();
mMatrix.set(mat);
mMatrix.setRotate(270);
bmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
bmp.getHeight(), mMatrix, false);
}
editPhoto1.setImageBitmap(bmp);
} catch (Exception e) {
Log.e("Exception Image Set :: ", e.getMessage());
}
}
4) Finally the image resizer class
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class ImageResizer {
public static Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options
options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
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;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
// 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)
}
}
Related
`Hi All, I would like to pick an image from my phone gallery and show it as a background of a imageview.I am able to show it and even I am able to make the image fit whole screen via(FITXY property of imageview).
The issue is image actually shrinks , so I tried Fitcenter and adjustviewbounds property etc and all other properties but no luck , with this properties image fits center and I can see some gaps in(width and height).
Could any one help me on how to fix this issue.
Here is my full code and screenshots for references.
<FrameLayout
android:id="#+id/fm"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:background="#70b29c"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/set"
android:contentDescription="#string/hello_world"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"/>
Here is my java code:
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMAGE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sc = (LinearLayout) findViewById(R.id.home);
Button wal = (Button) findViewById(R.id.setwall);
wal.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if (requestCode == RESULT_LOAD_IMAGE && resultCode ==RESULT_OK && null != data) {
Uri picUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(picUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
bitmapView = (ImageView) findViewById(R.id.set);
bitmapView.setImageBitmap(ExifUtils.rotateBitmap(filePath, decodeSampledBitmap(new File(filePath), 400, 800)));
bitmapView.setScaleType(ImageView.ScaleType.FIT_XY);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor edit = shre.edit();
edit.putString("profilePic", filePath);
edit.commit();
}
}
public Bitmap decodeSampledBitmap(File res, int reqWidth, int reqHeight) {
if (res != null) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
FileInputStream stream2 = new FileInputStream(res);
BitmapFactory.decodeStream(stream2, null, options);
stream2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Calculate inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
o2.inJustDecodeBounds = false;
FileInputStream stream = null;
try {
stream = new FileInputStream(res);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, o2);
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
} else
return null;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
}
Link for the screenshot here
Using FITXY will fit your image to the imageView regardless of the resolution or aspect ratio of image which will result in inappropriate display of image...
If you want your image to be displayed on the whole screen its better to use CENTER or CENTERCROP which will crop the selected image but set it in image's aspect ratio and will fully cover your view....
I want to take a single picture and put it in an imageView.I have managed to open the camera and every time i take a picture it lets me take another one.
This is my onCreate method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
File photo = dispatchTakePictureIntent();
ImageView imgView = (ImageView) findViewById(R.id.DisplayImageView);
if(photo.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(photo.getAbsolutePath());
imgView.setImageBitmap(myBitmap);
}
}
This is my taking picture method:
private File dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = null;
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Toast.makeText(this, "Failed to create the image file!", Toast.LENGTH_SHORT).show();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
return photoFile;
}
I need to get back to the activity from the camera after one photo and view it. How can i do that?
You need to Override onActivityResult() of your Activity to get the image and display it in ImageView. You should sample the image according to your needs when you get it from Camera and also to prevent your image from rotating while displaying in ImageView, you need to look for Exif params.
Here is the onActivityResult() code.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == RESULT_OK && requestCode == Constants.REQUEST_TAKE_PHOTO) {
// in case of taking pic from camera, you have to define filepath already and image get saved in that filepath you specified at the time when you started camera intent.So in your case it will be following
String filePath=photoFile.getAbsolutePath(); //photofile is the same file you passed while starting camera intent.
if (filePath != null) {
int orientation = 0;
private Bitmap imageBitmap;
try {
ExifInterface exif = new ExifInterface(filePath);
orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION, 1);
} catch (IOException e) {
e.printStackTrace();
}
try {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(
options, reqWidth, rewHeight);
options.inJustDecodeBounds = false;
imageBitmap = BitmapFactory.decodeFile(filePath,
options);
if (orientation == 6) {
Matrix matrix = new Matrix();
matrix.postRotate(90);
imageBitmap = Bitmap.createBitmap(imageBitmap,
0, 0, imageBitmap.getWidth(),
imageBitmap.getHeight(), matrix, true);
} else if (orientation == 8) {
Matrix matrix = new Matrix();
matrix.postRotate(270);
imageBitmap = Bitmap.createBitmap(imageBitmap,
0, 0, imageBitmap.getWidth(),
imageBitmap.getHeight(), matrix, true);
} else if (orientation == 3) {
Matrix matrix = new Matrix();
matrix.postRotate(180);
imageBitmap = Bitmap.createBitmap(imageBitmap,
0, 0, imageBitmap.getWidth(),
imageBitmap.getHeight(), matrix, true);
}
} catch (OutOfMemoryError e) {
imageBitmap = null;
e.printStackTrace();
} catch (Exception e) {
imageBitmap = null;
e.printStackTrace();
}
}
if (imageBitmap != null) {
// set this imageBitmap to your ImageView
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
and this is the sampling function
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Well in your Activity that does startActivityForResult override the following Method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}
Replace mImageView with the ImageView you want to show your image
I am a new bie in Android development.
Please bare with my english.
I struck with a problem where I am unable to show image from gallery in portrait mode,it is showing in landscape mode.Here is the code for your reference,Could you please help me to solve this issue.Thanks in Advance.
What I tried sofar is, I have gone through the below stackoverflow answers to the same issue and tried to place the same code in my class but the image still sits in landscape mode only.
Stackvoerflow links I followed are:
1.Open Image from Gallery Only in Potrait mode
2.http://codereply.com/answer/5xf8di/android-detect-image-orientation-portrait-landscape-picked-gallery-setting-imageview.html
3.Android: Bitmaps loaded from gallery are rotated in ImageView
public class FragmentTab1 extends Fragment {
RelativeLayout homes;
private static int RESULT_LOAD_IMAGE = 1;
ImageView bitmapView;
BitmapFactory.Options options;
String filePath;
Button rot;
private int mDegree = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View ima = inflater.inflate(R.layout.fragmenttab1, container, false);
homes = (RelativeLayout) ima.findViewById(R.id.hmt);
bitmapView = (ImageView) ima.findViewById(R.id.image);
homes.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
return false;
}
});
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
final String filePath = prefs.getString("profilePic", "");
if (!filePath.equals("")) {
bitmapView = (ImageView) ima.findViewById(R.id.image);
bitmapView.setImageBitmap(BitmapLoaderf.loadBitmap(filePath, 500, 500));
bitmapView.setScaleType(ImageView.ScaleType.FIT_XY);
}
return ima;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
Uri picUri = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(picUri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
filePath = cursor.getString(columnIndex);
cursor.close();
bitmapView.setImageBitmap(BitmapLoaderf.loadBitmap(filePath, 500, 500));
bitmapView.setScaleType(ImageView.ScaleType.FIT_XY);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(getActivity());
Editor edit = shre.edit();
edit.putString("profilePic", filePath);
edit.commit();
}
}
}
class BitmapLoaderf {
public static int getScale(int originalWidth, int originalHeight,
final int requiredWidth, final int requiredHeight) {
//a scale of 1 means the original dimensions
//of the image are maintained
int scale = 1;
//calculate scale only if the height or width of
//the image exceeds the required value.
if ((originalWidth > requiredWidth) || (originalHeight > requiredHeight)) {
//calculate scale with respect to
//the smaller dimension
if (originalWidth < originalHeight)
scale = Math.round((float) originalWidth / requiredWidth);
else
scale = Math.round((float) originalHeight / requiredHeight);
}
return scale;
}
public static BitmapFactory.Options getOptions(String filePath,
int requiredWidth, int requiredHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
//setting inJustDecodeBounds to true
//ensures that we are able to measure
//the dimensions of the image,without
//actually allocating it memory
options.inJustDecodeBounds = true;
//decode the file for measurement
BitmapFactory.decodeFile(filePath, options);
//obtain the inSampleSize for loading a
//scaled down version of the image.
//options.outWidth and options.outHeight
//are the measured dimensions of the
//original image
options.inSampleSize = getScale(options.outWidth,
options.outHeight, requiredWidth, requiredHeight);
//set inJustDecodeBounds to false again
//so that we can now actually allocate the
//bitmap some memory
options.inJustDecodeBounds = false;
return options;
}
public static Bitmap loadBitmap(String filePath,
int requiredWidth, int requiredHeight) {
BitmapFactory.Options options = getOptions(filePath,
requiredWidth, requiredHeight);
return BitmapFactory.decodeFile(filePath, options);
}
}
This is what I usually do :
public class ExifUtils {
public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
try {
int orientation = getExifOrientation(src);
if (orientation == 1) {
return bitmap;
}
Matrix matrix = new Matrix();
switch (orientation) {
case 2:
matrix.setScale(-1, 1);
break;
case 3:
matrix.setRotate(180);
break;
case 4:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case 5:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case 6:
matrix.setRotate(90);
break;
case 7:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case 8:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return oriented;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
private static int getExifOrientation(String src) throws IOException {
int orientation = 1;
try {
/**
* if your are targeting only api level >= 5 ExifInterface exif =
* new ExifInterface(src); orientation =
* exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
*/
if (Build.VERSION.SDK_INT >= 5) {
Class<?> exifClass = Class
.forName("android.media.ExifInterface");
Constructor<?> exifConstructor = exifClass
.getConstructor(new Class[] { String.class });
Object exifInstance = exifConstructor
.newInstance(new Object[] { src });
Method getAttributeInt = exifClass.getMethod("getAttributeInt",
new Class[] { String.class, int.class });
java.lang.reflect.Field tagOrientationField = exifClass
.getField("TAG_ORIENTATION");
String tagOrientation = (String) tagOrientationField.get(null);
orientation = (Integer) getAttributeInt.invoke(exifInstance,
new Object[] { tagOrientation, 1 });
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return orientation;
}
}
Then in the main Activity you call it like this:
image.setImageBitmap(ExifUtils.rotateBitmap(path, decodeSampledBitmap(new File(path), 400, 400)));
public Bitmap decodeSampledBitmap(File res, int reqWidth, int reqHeight) {
if (res != null) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
try {
FileInputStream stream2 = new FileInputStream(res);
BitmapFactory.decodeStream(stream2, null, options);
stream2.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Calculate inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
o2.inJustDecodeBounds = false;
FileInputStream stream = null;
try {
stream = new FileInputStream(res);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(stream, null, o2);
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
} else
return null;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
In this code you extract the bitmap from the file path, give it a certain height and width and pass it to the ExifUtils to show the bitmap in the correct way.
I think this wraps your class and more.
If you need anymore help I am more than ready to offer
I am developing one application in which I have to capture image from camera and add to ImageView. Here I have a problem while showing image on ImageView. If I click save button the image is not showing on ImageView for the first time,but for second time it is showing,please solve my problem, I am unable to find solution for this.
Code Snippet:
fromCamera.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* Log.e("OPEN", "CAMERA");
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, RESUL_CameraT_LOAD_IMAGE);*/
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(Environment.getExternalStorageDirectory()+File.separator +
"fav.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, RESUL_CameraT_LOAD_IMAGE);
uploadalertDialog.dismiss();
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = null;
Bitmap bitmap;
try {
switch (requestCode) {
case RESUL_CameraT_LOAD_IMAGE:
if (resultCode == Activity.RESULT_OK) {
// imageView.setImageResource(android.R.color.transparent);
Log.e("GET IMAGE", "PATH");
try{
File file = new File(Environment.getExternalStorageDirectory()+File.separator
+ "fav.jpg");
bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 300, 300);
uloadImgView.setImageBitmap(bitmap);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90,
byteArray);
byte[] byte_arr = byteArray.toByteArray();
base64 = Base64.encodeToString(byte_arr, Base64.DEFAULT);
}
catch(Exception e){
e.printStackTrace();
}
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight)
{ // BEST QUALITY MATCH
//First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize, Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
options.inPreferredConfig = Bitmap.Config.RGB_565;
int inSampleSize = 1;
if (height > reqHeight)
{
inSampleSize = Math.round((float)height / (float)reqHeight);
}
int expectedWidth = width / inSampleSize;
if (expectedWidth > reqWidth)
{
//if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
inSampleSize = Math.round((float)width / (float)reqWidth);
}
options.inSampleSize = inSampleSize;
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
First of all add the following permission in you app's manifest file
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Then check the following code which I used in my application to set s user's profile pic.
// on click listener for the camera trigger
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent cameraintent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraintent, 101);
}
});
//onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Uri selectedImage = null;
Bitmap bitmap;
try {
switch (requestCode) {
case 101:
if (resultCode == Activity.RESULT_OK) {
if (null != data) {
selectedImage = data.getData(); // the uri of the image
// taken
bitmap = decodeSampledBitmapFromUri(this,
selectedImage, 100, 100);
image.setImageBitmap(bitmap);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}
//Bitmap sampling
public static Bitmap decodeSampledBitmapFromUri(Activity callingActivity,
Uri uri, int reqWidth, int reqHeight) {
try {
InputStream input = callingActivity.getContentResolver()
.openInputStream(uri);
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 2; // make the bitmap size half of the
// original one
BitmapFactory.decodeStream(input, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
input.close();
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
input = callingActivity.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, options);
return bitmap;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} catch (IOException e) {// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
//calculate sample size
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
I am making a project in which wallpapers will be changed after every 5 seconds. I am able to set wallpaper but it is setting the wallpaper by cropping the image. I want to set the wallpaper in its actual size what must i do regarding this?
BitmapFactory.decodeFile(list.get(i));
options.inJustDecodeBounds = false;
if (myBitmap != null) {
myBitmap.recycle();
myBitmap = null;
}
Bitmap decodedSampleBitmap = BitmapFactory.decodeFile(list
.get(i));
// here height and width are the height and width of the display screen
myBitmap = Bitmap.createScaledBitmap(decodedSampleBitmap,
width, height, true);
if (decodedSampleBitmap != myBitmap)
decodedSampleBitmap.recycle();
decodedSampleBitmap = null;
WallpaperManager wm = WallpaperManager
.getInstance(WallService.this);
try {
Log.i("In Service", "before set wallpaper");
wm.setBitmap(myBitmap);
Log.i("In Service", "after set wallpaper");
Thread.sleep(5000);
Log.i("In Service", "after thread");
} catch (Exception e) {
Log.e("Exception", "Cannot set image as wallpaper", e);
}
Update 1:
If i use this code the wallpaper is settingup with image's actual size.
Now i am having a small problem i.e when i open the app again and click on select photos button the photos are not displaying in custom gallery
for (int i = 0; i <= list.size(); i++) {
if (i == list.size()) {
i = 0;
}
BitmapFactory.decodeFile(list.get(i));
options.inJustDecodeBounds = false;
if (myBitmap != null) {
myBitmap.recycle();
myBitmap = null;
}
if (decodedSampleBitmap != null) {
decodedSampleBitmap.recycle();
decodedSampleBitmap = null;
}
decodedSampleBitmap = BitmapFactory.decodeFile(list
.get(i));
//myBitmap = Bitmap.createScaledBitmap(decodedSampleBitmap, width, height, true);
/*if (decodedSampleBitmap != myBitmap)
decodedSampleBitmap.recycle();
decodedSampleBitmap = null;
*/
WallpaperManager wm = WallpaperManager
.getInstance(WallService.this);
try {
Log.i("In Service", "before set wallpaper");
wm.setBitmap(decodedSampleBitmap);
Log.i("In Service", "after set wallpaper");
Thread.sleep(5000);
Log.i("In Service", "after thread");
} catch (Exception e) {
Log.e("Exception", "Cannot set image as wallpaper", e);
}
}
in activity class... i am getting the log "button clicked" but i am not getting the log "in on activity result"
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnAddPhots:
Intent intent = new Intent(MainActivity.this,
CustomPhotoGalleryActivity.class);
startActivityForResult(intent, PICK_IMAGE_MULTIPLE);
Log.i("Main Activity", "button clicked");
break;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("Main Activity", "in on activity result");
if (resultCode == RESULT_OK) {
Log.i("Main Activity", "in if1");
if (requestCode == PICK_IMAGE_MULTIPLE) {
Log.i("Main Activity", "in if2");
imagesPathList = new ArrayList<String>();
String[] imagesPath = data.getStringExtra("data").split("\\|");
try {
Log.i("Main Activity", "in try");
lnrImages.removeAllViews();
} catch (Throwable e) {
Log.i("Main Activity", "in catch");
e.printStackTrace();
}
Update 2..
I tried it earlier also i tried it now again it is stting up the background colour of the image only as wallpaper. If i use the Update1 code it is working goog but not awesome
Public class WallService extends Service {
ArrayList<String> list;
Bitmap myBitmap;
int width, height;
Bitmap decodedSampleBitmap = null;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.i("on create", "Service Created");
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
list = intent.getStringArrayListExtra("Imagess");
width = intent.getExtras().getInt("Width");
height = intent.getExtras().getInt("Height");
Log.i("Width= ", "" + width);
Log.i("Height= ", "" + height);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
int h = 0;
int w = 0;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
for (int i = 0; i <= list.size(); i++) {
if (i == list.size()) {
i = 0;
}
BitmapFactory.decodeFile(list.get(i));
options.inJustDecodeBounds = false;
if (myBitmap != null) {
myBitmap.recycle();
myBitmap = null;
}
if (decodedSampleBitmap != null) {
decodedSampleBitmap.recycle();
decodedSampleBitmap = null;
}
decodedSampleBitmap = decodeSampledBitmapFromFile(list.get(i),
w, h);
// myBitmap = Bitmap.createScaledBitmap(decodedSampleBitmap,
// width, height, true);
/*
* if (decodedSampleBitmap != myBitmap)
* decodedSampleBitmap.recycle(); decodedSampleBitmap = null;
*/
WallpaperManager wm = WallpaperManager
.getInstance(WallService.this);
try {
Log.i("In Service", "before set wallpaper");
wm.setBitmap(decodedSampleBitmap);
Log.i("In Service", "after set wallpaper");
Thread.sleep(5000);
Log.i("In Service", "after thread");
} catch (Exception e) {
Log.e("Exception", "Cannot set image as wallpaper", e);
}
}
return "Executed";
}
public Bitmap decodeSampledBitmapFromFile(String path, int width,
int height) {
// TODO Auto-generated method stub
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// String imageType = options.outMimeType;
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
public int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// TODO Auto-generated method stub
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
// Log.d(MainActivity.TAG, " in sample Size: " + inSampleSize);
return inSampleSize;
}
}
I already answered a similar question some time ago: How to set wallpaper permanently in android
I've created a simple app to change the wallpaper randomly too, The code of the full file is here Maybe is what you want (The two key functions here are decodeSampledBitmapFromFile and calculateInSampleSize:
private void changeWallPaper(int h, int w){
String path = getRandomFile();
Bitmap bm = decodeSampledBitmapFromFile(path, w, h);
try {
WallpaperManager mywall = WallpaperManager.getInstance(this);
Log.i(MainActivity.TAG, "Setting wallpaper to " + path);
mywall.setBitmap(bm);
} catch (IOException e) {
Log.e(MainActivity.TAG, "Cannot set image as wallpaper", e);
}
}
public static Bitmap decodeSampledBitmapFromFile(String path, int width, int height) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
//String imageType = options.outMimeType;
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, width, height);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
/**
*
* #param options
* #param reqWidth
* #param reqHeight
* #return int
* #see http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height
/ (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
Log.d(MainActivity.TAG, " in sample Size: " + inSampleSize);
return inSampleSize;
}