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;
}
Related
I am using Camera Kit Library on that activity the memory usage is too much in app app what could be the possible issue?
This is a camera view activity which uses camera Kit Library. Camera Results are received when user clicks captureButton and cameraView.captureImage() is called and results are sent to next Preview Activity. But i am seeing huge memory usage when just activity is opened and no image is captured yet.
My activity Code:
public class PSLSelfieActivity extends AppCompatActivity {
private CameraKitView cameraView;
private FloatingActionButton captureButton, switchCamera, useGallery;
private String TAG = "ramiz";
private int orientation = 0;//0=pot,1=land
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pslselfie);
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
try {
cameraView = findViewById(R.id.camera);
captureButton = findViewById(R.id.captureButton);
useGallery = findViewById(R.id.useGalleryButton);
OrientationEventListener mOrientationListener = new OrientationEventListener(
getApplicationContext()) {
#Override
public void onOrientationChanged(int orientation) {
PSLSelfieActivity.this.orientation = orientation;
}
};
if (mOrientationListener.canDetectOrientation()) {
mOrientationListener.enable();
}
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.captureImage(new CameraKitView.ImageCallback() {
#Override
public void onImage(CameraKitView cameraKitView, byte[] bytes) {
Intent i = new Intent(PSLSelfieActivity.this, PSLSelfiePreview.class);
Bitmap b = loadBitmap(bytes);
Log.d(TAG, "OnCaptureImage: Bitmap Size= w=" + b.getWidth() + " h=" + b.getHeight());
PSLSelfiePreview.inputImage = b;
i.putExtra("orientation", orientation);
i.putExtra("flipImage", true);
startActivity(i);
}
});
}
});
useGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, USE_GALLERY_REQUEST);
}
});
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getContext(), "There is some error with opening camera.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == USE_GALLERY_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
try {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
Intent i = new Intent(PSLSelfieActivity.this, PSLSelfiePreview.class);
Bitmap b = loadBitmap(imageUri);
Log.d(TAG, "onActivityResult: Bitmap Size= w=" + b.getWidth() + " h=" + b.getHeight());
PSLSelfiePreview.inputImage = b;
i.putExtra("orientation", 0);
i.putExtra("flipImage", false);
startActivity(i);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getContext(), "Cannot Load Image.", Toast.LENGTH_SHORT).show();
} catch (OutOfMemoryError e) {
e.printStackTrace();
Toast.makeText(getContext(), "Cannot Load Image. Image too Large.", Toast.LENGTH_SHORT).show();
}
} else {
}
}
}
#Override
protected void onStart() {
cameraView.onStart();
super.onStart();
}
#Override
protected void onResume() {
cameraView.onResume();
super.onResume();
}
#Override
protected void onPause() {
cameraView.onPause();
super.onPause();
}
#Override
protected void onStop() {
cameraView.onStop();
super.onStop();
}
#Override
protected void onDestroy() {
System.gc();
super.onDestroy();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
cameraView.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
System.gc();
}
public Bitmap loadBitmap(byte[] bytes) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
Bitmap b = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
options.inSampleSize = calculateInSampleSize(options, 480, 640);
Log.d(TAG, "loadBitmap: inSampleSize=" + options.inSampleSize);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
}
public Bitmap loadBitmap(Uri imageUri) throws IOException {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
final InputStream imageStream;
imageStream = getContentResolver().openInputStream(imageUri);
Bitmap b = BitmapFactory.decodeStream(imageStream, null, options);
options.inSampleSize = calculateInSampleSize(options, 480, 640);
Log.d(TAG, "loadBitmap: inSampleSize=" + options.inSampleSize);
options.inJustDecodeBounds = false;
final InputStream imageStreamNew;
imageStreamNew = getContentResolver().openInputStream(imageUri);
Bitmap outBitmap = BitmapFactory.decodeStream(imageStreamNew, null, options);
if (imageStream != null) {
imageStream.close();
}
if (imageStreamNew != null) {
imageStreamNew.close();
}
return outBitmap;
}
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;
Log.d(TAG, "calculateInSampleSize: h=" + height + " - w=" + width);
if (width > height) {
int temp = reqHeight;
reqHeight = reqWidth;
reqWidth = temp;
}
Log.d(TAG, "calculateInSampleSize: updated h=" + height + " - w=" + width);
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;
}
private Context getContext() {
return this;
}
}
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
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)
}
}
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'm trying to open an image from a specific uri, checking if this image is too big to resize it, and return it as Base64. My problem is the code I have to resize image never resize images (never indicate that the image is too big). I looked for others questions similar this, but I didn't get any answer.
I don't know why always in this two code lines the values are -1:
final int height = options.outHeight; // Always -1 WHY?
final int width = options.outWidth; // Always -1 WHY?
I attach my code:
private class WriteImage extends AsyncTask<Object, Void, String>{
private static Bitmap decodeSampledBitmapFromStream(InputStream is,
int reqWidth,
int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream aux = inputStreamCopy(is);
BitmapFactory.decodeStream(is, null, options); // SkImageDecoder::Factory returned null
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(aux, null, options);
}
private static InputStream inputStreamCopy(InputStream is) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[1024];
try {
while ((len = is.read(buffer)) > -1) baos.write(buffer, 0, len);
} catch (IOException e) {
e.printStackTrace();
}
return new ByteArrayInputStream(baos.toByteArray());
}
private static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight; // Always -1 WHY?
final int width = options.outWidth; // Always -1 WHY?
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height)
inSampleSize = Math.round((float)height / (float)reqHeight);
else
inSampleSize = Math.round((float)width / (float)reqWidth);
// 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).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down
// further.
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap)
inSampleSize++;
}
for (int i=5; i>0; i--){
if (Math.pow(2, i)<=inSampleSize){
inSampleSize = (int) Math.pow(2, i);
break;
}
}
return inSampleSize;
}
#Override
protected void onPreExecute(){
}
#Override
protected void onProgressUpdate(Void... values){
}
#Override
protected String doInBackground(Object... params) {
try {
InputStream is = ((android.app.Activity) params[1]).getContentResolver().openInputStream((Uri) params[0]);
Bitmap bitmap = decodeSampledBitmapFromStream(is, 300, 300);
int bytes = bitmap.getWidth()*bitmap.getHeight()*4;
ByteBuffer buffer = ByteBuffer.allocate(bytes);
bitmap.copyPixelsToBuffer(buffer);
return Base64.encodeToString(buffer.array(), Base64.DEFAULT);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
}
}
The solution was this! Replace the following:
In decodeSampledBitmapFromStream function:
private Bitmap decodeSampledBitmapFromStream(InputStream is,
int reqWidth,
int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream aux = inputStreamCopy(is);
BitmapFactory.decodeStream(aux, null, options); // SkImageDecoder::Factory returned null
try {
aux.reset();
} catch (IOException e) {
e.printStackTrace();
}
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(aux, null, options);
}
And in doInBackground method:
#Override
protected String doInBackground(Object... params) {
try {
InputStream is = ((android.app.Activity) params[1]).getContentResolver().openInputStream((Uri) params[0]);
Bitmap bitmap = decodeSampledBitmapFromStream(is, 300, 300);
System.gc();
int bytes = bitmap.getWidth()*bitmap.getHeight()*2;
ByteBuffer buffer = ByteBuffer.allocate(bytes);
bitmap.copyPixelsToBuffer(buffer);
return Base64.encodeToString(buffer.array(), Base64.DEFAULT);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
:)