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;
}
}
Related
I want to create 2 buttons : when I click to button1 the model1 is initialized and when I click on button2 the model2 is initialized so I created new activity (MainSecond.java) where I created the 2 buttons and send their ids to MainActivity where the 2 models initialized
the problem is when I click on any of the two buttons the 2 models are initialized
this is my code :
MainSecond.java
public class MainSecond extends Activity {
public Button button1;
public Button button2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BackToMain(R.id.button1);
// BackToMain(view);
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
BackToMain(R.id.button1);
}
});
}
public void BackToMain(int button_id) {
Intent intent = new Intent(MainSecond.this, MainActivity.class);
intent.putExtra("name",button_id);
intent.putExtra("name",button_id);
startActivity(intent);
}
MainActivity.java
initialization of 2 models
public class InitializeModelAsyncTask extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
final boolean ret = DeeplabModel.initialize();
Logger.debug("initialize deeplab model: %s", ret);
return ret;
}
}
public class InitializeModelAsyncTask2 extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... voids) {
final boolean ret2 = DeeplabModel2.initialize();
Logger.debug("initialize deeplab model: %s", ret2);
return ret2;
}
}
getting buttons ids :
public void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buckyButton = findViewById(R.id.buckysButton);
// src_img =(ImageView) findViewById(R.id.src_img) ;
Intent mIntent=getIntent();
int intval=mIntent.getIntExtra("buttonid",0);
if(intval==R.id.button1){
initModel();
}
if(intval==R.id.button2){
initModel2();
}
}
private void syncUIWithPermissions(boolean requestIfNeed) {
final boolean granted = checkRequiredPermissions(requestIfNeed);
setPickImageEnabled(granted);
setPickImageEnabled2(granted);
if (granted && !DeeplabModel.isInitialized()) {
initModel();
}
else if (granted && !DeeplabModel2.isInitialized()) {
initModel2();
}
}
private boolean checkRequiredPermissions() {
return checkRequiredPermissions(false);
}
private boolean checkRequiredPermissions(boolean requestIfNeed) {
final boolean writeStoragePermGranted =
ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED;
Logger.debug("storage permission granted: %s", writeStoragePermGranted);
if (!writeStoragePermGranted
&& requestIfNeed) {
requestRequiredPermissions();
}
return writeStoragePermGranted;
}
private void requestRequiredPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
},
REQUEST_REQUIRED_PERMISSION);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Logger.debug("requestCode = 0x%02x, permission = [%s], grant = [%s]",
requestCode,
ArrayUtils.stringArrayToString(permissions, ","),
ArrayUtils.intArrayToString(grantResults));
if (requestCode == REQUEST_REQUIRED_PERMISSION) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Logger.debug("permission granted, initialize model.");
initModel();
initModel2();
}
the initMode() and intitModel2() functions are :
private void initModel() {
new InitializeModelAsyncTask().execute((Void)null);
}
private void initModel2() {
new InitializeModelAsyncTask2().execute((Void)null);
}
this is the code that is used to show the 2 models on the screen
public class SegmentBitmapsLoader extends AbsAsyncDataLoader<List<SegmentBitmap>> {
private Uri mImageUri;
public SegmentBitmapsLoader(Context context, Uri imageUri) {
super(context);
mImageUri = imageUri;
}
#Nullable
#Override
public List<SegmentBitmap> loadInBackground() {
final Context context = getContext();
if (context == null) {
return null;
}
final Resources res = context.getResources();
if (res == null) {
return null;
}
if (mImageUri == null) {
return null;
}
final String filePath = FilePickUtils.getPath(context, mImageUri);
Logger.debug("file to mask: %s", filePath);
if (TextUtils.isEmpty(filePath)) {
return null;
}
boolean vertical = checkAndReportDimen(filePath);
final int dw = res.getDimensionPixelSize(
vertical ? R.dimen.image_width_v : R.dimen.image_width_h);
final int dh = res.getDimensionPixelSize(
vertical ? R.dimen.image_height_v : R.dimen.image_height_h);
Logger.debug("display image dimen: [%d x %d]", dw, dh);
Bitmap bitmap = decodeBitmapFromFile(filePath, dw, dh);
if (bitmap == null) {
return null;
}
List<SegmentBitmap> bitmaps = new ArrayList<>();
bitmaps.add(new SegmentBitmap(R.string.label_original, bitmap));//important note
final int w = bitmap.getWidth();
final int h = bitmap.getHeight();
Logger.debug("decoded file dimen: [%d x %d]", w, h);
EventBus.getDefault().post(new ImageDimenEvent(mImageUri, w, h));
float resizeRatio = (float) DeeplabModel.INPUT_SIZE / Math.max(bitmap.getWidth(), bitmap.getHeight());
float resizeRatio2 = (float) DeeplabModel2.INPUT_SIZE / Math.max(bitmap.getWidth(), bitmap.getHeight());
int rw = Math.round(w * resizeRatio);
int rh = Math.round(h * resizeRatio);
int rw2 = Math.round(w * resizeRatio2);
int rh2 = Math.round(h * resizeRatio2);
Logger.debug("resize bitmap: ratio = %f, [%d x %d] -> [%d x %d]",
resizeRatio, w, h, rw, rh);
Logger.debug("resize bitmap: ratio = %f, [%d x %d] -> [%d x %d]",
resizeRatio2, w, h, rw2, rh2);
Bitmap resized = ImageUtils.tfResizeBilinear(bitmap, rw, rh);
Bitmap resized2 = ImageUtils.tfResizeBilinear(bitmap, rw2, rh2);
Bitmap mask = DeeplabModel.segment(resized);
Bitmap mask2 = DeeplabModel2.segment(resized2);
if (mask != null) {
mask = BitmapUtils.scaleBitmap(mask, w, h);
bitmaps.add(new SegmentBitmap(R.string.label_mask, mask));
final Bitmap cropped = cropBitmapWithMask(bitmap, mask);
bitmaps.add(new SegmentBitmap(R.string.label_cropped, cropped));
}
else {
bitmaps.add(new SegmentBitmap(R.string.label_mask, (Bitmap) null));
bitmaps.add(new SegmentBitmap(R.string.label_cropped, (Bitmap) null));
}
if(mask2 != null){
mask2 = BitmapUtils.scaleBitmap(mask2, w, h);
bitmaps.add(new SegmentBitmap(R.string.label_mask, mask2));
final Bitmap cropped = cropBitmapWithMask(bitmap, mask2);
bitmaps.add(new SegmentBitmap(R.string.label_cropped, cropped));
}
else {
bitmaps.add(new SegmentBitmap(R.string.label_mask, (Bitmap)null));
bitmaps.add(new SegmentBitmap(R.string.label_cropped, (Bitmap)null));
}
return bitmaps;
}
private boolean checkAndReportDimen(String filePath) {
if (TextUtils.isEmpty(filePath)) {
return false;
}
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
final int width = options.outWidth;
final int height = options.outHeight;
Logger.debug("original image dimen: %d x %d", width, height);
EventBus.getDefault().post(new ImageDimenEvent(mImageUri, width, height));
return (height > width);
}
private Bitmap cropBitmapWithMask(Bitmap original, Bitmap mask) {
if (original == null
|| mask == null) {
return null;
}
final int w = original.getWidth();
final int h = original.getHeight();
if (w <= 0 || h <= 0) {
return null;
}
Bitmap cropped = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(cropped);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
canvas.drawBitmap(original, 0, 0, null);
canvas.drawBitmap(mask, 0, 0, paint);
paint.setXfermode(null);
return cropped;
}
public static Bitmap decodeBitmapFromFile(String filePath,
int reqWidth,
int reqHeight) {
if (TextUtils.isEmpty(filePath)) {
return null;
}
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
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;
}
}
Well you are sending the same button id for both the buttons...
When you call BacktoMain method for both the buttons you are sending button1 id.
Change the line inside button2.onClickListener from
BackToMain(R.id.button1);
to
BackToMain(R.id.button2);
Do this...
public void BackToMain(int button_id) {
Intent intent = new Intent(MainSecond.this, MainActivity.class);
intent.putExtra("name",button_id);
intent.putExtra("name",button_id); //remove this line y do the same thing twice
startActivity(intent);
}
And...
Intent mIntent=getIntent();
int intval=mIntent.getIntExtra("name",0);
//should give you the button id and returns 0 if
//value for the key "name" was not given
if(intval==R.id.button1){
initModel();
}
if(intval==R.id.button2){
initModel2();
}
Try these changes and lemme know if it works..
I need to take pictures from camera and gallery and do certain some functionality,This needs to be done from two places(fragments),
How can i write common code.Is it possible,Like a base class?
private static final int PICK_IMAGE = 1;
int REQUEST_CAMERA = 0;
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.addProductImage:
selectImage();
break;
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, REQUEST_CAMERA);
} else if (items[item].equals("Choose from Library")) {
selectImageFromGallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == getActivity().RESULT_OK && requestCode == 1 && null != data) {
decodeUri(data.getData());
} else if (resultCode == getActivity().RESULT_OK && requestCode == REQUEST_CAMERA) {
// File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
captureImage();
}
}
This Method is to capture image from Camera
private void captureImage() {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 500, 250);
// set the bitmap here to image view
image.setImageBitmap(bitmap);
}
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;
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
This method is to select image from Galary
public void selectImageFromGallery() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
}
public void decodeUri(Uri uri) {
ParcelFileDescriptor parcelFD = null;
try {
parcelFD = getActivity().getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor imageSource = parcelFD.getFileDescriptor();
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(imageSource, null, o);
// the new size we want to scale to
final int REQUIRED_SIZE = 1024;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE) {
break;
}
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
bitmap = BitmapFactory.decodeFileDescriptor(imageSource, null, o2);
// set the bitmap here to image view
image.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Utility.showToat(mContext, " File Not Found Exception ");
} finally {
if (parcelFD != null)
try {
parcelFD.close();
} catch (IOException e) {
// ignored
}
}
}
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 want to upload the high quality image to server and get it in Imageview in my app. I'm able to do so. But the problem is quality of image which is very low. How can i upload the desire resolution of image to server and get it in imageview. Help me. Thanks
Here is my Code:
public class ChangeProfileActivity extends Activity {
ImageView updateBT, IV;
private SharedPreferences saveImagePref;
private SharedPreferences.Editor saveImagePrefEditor;
protected static final int CAMERA_REQUEST = 0;
protected static final int GALLERY_PICTURE = 1;
private Intent pictureActionIntent = null;
Bitmap bitmap;
private TouchImageView touch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_change_profile);
updateBT = (ImageView) findViewById(R.id.buttonUpdate);
dialog = new AlertDialogCheck(ChangeProfileActivity.this);
IV = (ImageView) findViewById(R.id.PersonalPictureIV);
saveImagePref = getSharedPreferences("saveImage", MODE_PRIVATE);
saveImagePrefEditor = saveImagePref.edit();
saveDOBPref = getSharedPreferences("saveImage", MODE_PRIVATE);
saveDOBPrefEditor = saveImagePref.edit();
registerForContextMenu(IV);
A = saveImagePref.getString("SAVE", "0");
bitmap = StringToBitMap(A);
if (bitmap != null) {
bitmap = Bitmap.createScaledBitmap(bitmap, 250, 250, false);
IV.setImageBitmap(bitmap);
}
if (bitmap == null) {
bitmap = BitmapFactory.decodeResource(this.getResources(),
R.drawable.user_profile_image);
IV.setImageBitmap(bitmap);
IV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
startDialog();
uploadImage();
}
});
}
IV.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startDialog();
}
});
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
}
private void startDialog() {
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Upload Pictures Option");
myAlertDialog.setMessage("How do you want to set your picture?");
myAlertDialog.setPositiveButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(
Intent.ACTION_GET_CONTENT, null);
pictureActionIntent.setType("image/*");
pictureActionIntent.putExtra("return-data", true);
startActivityForResult(pictureActionIntent,
GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
pictureActionIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(pictureActionIntent,
CAMERA_REQUEST);
}
});
myAlertDialog.show();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICTURE) {
if (resultCode == RESULT_OK) {
if (data != null) {
// our BitmapDrawable for the thumbnail
BitmapDrawable bmpDrawable = null;
// try to retrieve the image using the data from the intent
Cursor cursor = getContentResolver().query(data.getData(),
null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(ImageColumns.DATA);
String fileSrc = cursor.getString(idx);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=1;
bitmap = BitmapFactory.decodeFile(fileSrc);
bitmap = Bitmap.createScaledBitmap(bitmap, 250, 250,
true);
saveImagePrefEditor.clear();
saveImagePrefEditor.commit();
saveImagePrefEditor.putString("SAVE",
BitMapToString(bitmap));
saveImagePrefEditor.commit();
IV.setImageBitmap(bitmap);
// touch.setImageBitmap(bitmap);+
A = saveImagePref.getString("SAVE", "0");
uploadImage();
} else {
bmpDrawable = new BitmapDrawable(getResources(), data
.getData().getPath());
IV.setImageDrawable(bmpDrawable);
// touch.setImageBitmap(bitmap);
A = saveImagePref.getString("SAVE", "0");
uploadImage();
}
} else {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
}
} else if (requestCode == CAMERA_REQUEST) {
if (resultCode == RESULT_OK) {
if (data.hasExtra("data")) {
bitmap = (Bitmap) data.getExtras().get("data");
bitmap = Bitmap.createScaledBitmap(bitmap, 250, 250, false);
saveImagePrefEditor.clear();
saveImagePrefEditor.commit();
saveImagePrefEditor.putString("SAVE",
BitMapToString(bitmap));
saveImagePrefEditor.commit();
// update the image view with the bitmap
IV.setImageBitmap(bitmap);
// touch.setImageBitmap(bitmap);
A = saveImagePref.getString("SAVE", "0");
uploadImage();
} else if (data.getExtras() == null) {
Toast.makeText(getApplicationContext(),
"No extras to retrieve!", Toast.LENGTH_SHORT)
.show();
BitmapDrawable thumbnail = new BitmapDrawable(
getResources(), data.getData().getPath());
// update the image view with the newly created drawable
IV.setImageDrawable(thumbnail);
// touch.setImageBitmap(bitmap);
A = saveImagePref.getString("SAVE", "0");
uploadImage();
}
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Cancelled",
Toast.LENGTH_SHORT).show();
} }
}
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String temp = Base64.encodeToString(b, Base64.DEFAULT);
return temp;
}
public Bitmap StringToBitMap(String encodedString) {
try {
byte[] encodeByte = Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
encodeByte.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}}
}
You can use android best practice.
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;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static Bitmap decodeFile(int width , int height ,File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = calculateInSampleSize(o, width, height);
//System.out.println("Scale: " + scale);
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
//System.out.println("--- exception "+e.toString());
e.printStackTrace();
}
return null;
}
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;
}