how to take screenshot and not save it on gallery in android - android

I use below code for ScreenShot:
public class startActivity{
Bitmap layoutBitmap = Bitmap.createBitmap(mReLayout.getWidth(), mReLayout.getHeight(), Bitmap.Config.ARGB_4444);
Canvas canvas = new Canvas(layoutBitmap);
mReLayout.draw(canvas);
Uri uri = getImageUri(getApplicationContext(), layoutBitmap);
Intent mIntent = new Intent(CategoryActivity.this, MainActivity.class);
mIntent.putExtra(Constant.BYTE_IMAGE, uri.toString());
startActivity(mIntent);
}
MainActivity.class
private void setUpImageBitmap() {
Uri uri = Uri.parse(getIntent().getExtras().getString(Constant.BYTE_IMAGE));
String selectedImagePath = getPath(uri);
mImageCube.setImageBitmap(Utils.decodeSampledBitmapFromResource(selectedImagePath, 200, 200));
}
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
Class Utils
public static Bitmap decodeSampledBitmapFromResource(String resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(resId, 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 = 2;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
How can I take a screenshot without saving it in the gallery?

Here Below code for how to take screenshot for any android control, means ImageView or Layout. below code for ImageView.
ImageView iv = (ImageView) findViewById(R.id.imageView1);
View v1 = getWindow().getDecorView().getRootView();
// View v1 = iv.getRootView(); //even this works
// View v1 = findViewById(android.R.id.content); //this works too
// but gives only content
v1.setDrawingCacheEnabled(true);
myBitmap = v1.getDrawingCache();
saveBitmap(myBitmap);
saveBitmap(myBitmap);
public void saveBitmap(Bitmap bitmap) {
String filePath = Environment.getExternalStorageDirectory()
+ File.separator + "Pictures/screenshot.png";
String nomedia = Environment.getExternalStorageDirectory()
+ File.separator + "Pictures/.nomedia";
File nomediaFile= new File(nomedia);
if(!nomediaFile.exists()){
nomediaFile.createNewFile();
}
File imagePath = new File(filePath);
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
sendMail(filePath);
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
Now you dont want to show any images in gallery then you have to ceate .nomedia file in folder of screenshot save. see below code for that.
String nomedia = Environment.getExternalStorageDirectory()
+ File.separator + "Pictures/.nomedia";
File nomediaFile= new File(nomedia);
if(!nomediaFile.exists()){
nomediaFile.createNewFile();
}
Above code already implemented in saveBitmap() method. I think help you for you this...
Now you want to share this image then get path of image and share with below code.
public void shareImage(String path) {
Uri myUri = Uri.parse("file://" + path);
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_TEXT, "Hello");
shareIntent.putExtra(Intent.EXTRA_STREAM, myUri);
shareIntent.setType("image/jpeg");
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(shareIntent, "send"));
}

The image files have to be stored somewhere. I think your actual question is how to hide image files from the gallery app.
To hide them from your gallery app there are two ways doing this:
1. Create a .nomedia file:
In the folder where you save your images (given by uri) you have to create a file with the name .nomedia.
2. Prefix folder with a dot:
You can rename the folder itself with a dot. Example: .images.

Related

How can I save image taken from camera into internal storage

I have this code that take photo and save to external storage, what I want is save to internal storage, please help me... what I should change to save to internal storage...
thank you
public class MainActivity extends AppCompatActivity {
public static final int CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE = 1777;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check that request code matches ours:
if (requestCode == CAPTURE_IMAGE_FULLSIZE_ACTIVITY_REQUEST_CODE) {
//Get our saved file into a bitmap object:
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
Bitmap bitmap = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
}
}
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) {
//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);
}
}
You can try this code to save your image to internal storage:
FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
// You can also use .JPG
yourBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
}
catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage());
}
catch (IOException e) {
Log.e(TAG, e.getMessage());
} finally {
fos.close();
}
You can also have a look at this: https://developer.android.com/guide/topics/data/data-storage.html#filesInternal
EDIT
For saving your full size image file to internal storage, you'll have to change your
File file = new File(Environment.getExternalStorageDirectory()+File.separator + "image.jpg");
to
File file = new File(context.getFilesDir(), "image.jpg");
getFilesDir() returns internal directory of your app. You will find more detailed information here: https://developer.android.com/training/basics/data-storage/files.html#WriteInternalStorage

Android crop image to store in database using rest api

I have a bunch of code that works fine when I'm not applying crop activity
but i wanted to apply crop to the selected image and send it to server using Rest API
TypedFile typedFile = new TypedFile("multipart/form-data",savedFileDestination);
initiateProgressDialog();
How to set cropped URI instead of savedFileDestination so that it takes cropped image path as file ?
Use the below method to crop:
public static Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
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) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
Thanks For all your answers and comments I found my solution it was that i have to firstly store my croped image into a file diectory because the croped image stores in the cache memory and we need the file path and send the file path to server to store it..... Thanks again
On click of camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File outPutFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "Path of your custom directory);
if (!outPutFile.exists()) {
outPutFile.mkdirs();
}
Uri capturedImageUri = Uri.fromFile(File.createTempFile("Your app directory name" + System.currentTimeMillis(), ".jpg", outPutFile));
Logg.e(getClass().getSimpleName(), "Captured_Pic ===== " + Uri.fromFile(outPutFile));
intent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(intent, Util.REQUEST_CAMERA);
On click of Gallery
CropImage.startPickImageActivity(HomeActivity.this);
OnActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case Util.REQUEST_CAMERA: // Camera request
startCropImageActivity(capturedImageUri);
break;
case CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE: // Crop
CropImage.ActivityResult result = CropImage.getActivityResult(data);
try {
if (resultCode == RESULT_OK) {
resultUri = result.getUri();
mProfileView.setImageURI(Uri.parse(resultUri.toString())); // this is my imageview, where I'll set that cropped image Uri.
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
} catch (Exception e) {
e.printStackTrace();
}
break;
case CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE: // Gallery request
try {
Uri selectedImageUri = CropImage.getPickImageResultUri(this, data);
startCropImageActivity(selectedImageUri);
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
}
This method will set property to cropping image tool according to your requirement
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setCropShape(CropImageView.CropShape.RECTANGLE)
.setActivityMenuIconColor(ContextCompat.getColor(HomeActivity.this, R.color.app_blue))
.setGuidelinesColor(ContextCompat.getColor(HomeActivity.this, R.color.app_blue))
.setScaleType(CropImageView.ScaleType.FIT_CENTER)
.setFixAspectRatio(true)
.setBorderCornerColor(ContextCompat.getColor(HomeActivity.this, R.color.app_blue))
.setBorderLineColor(ContextCompat.getColor(HomeActivity.this, R.color.app_blue))
.start(this);
}

ANDROID HUAWEI device -> cannot get photo URI

im taking photo by using this method:
public void takePhoto () {
try {
Log.i(GlobalApplication.APP_LOG_NAMESPACE, "Trying to take photo");
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
} catch (Exception e) {
Log.e(GlobalApplication.APP_LOG_NAMESPACE, "takePhoto method cannot be processed", e);
e.printStackTrace();
}
}
On some devices i got always in onActivity result in image URI null (especially on Huawei devices).
I tried to find any working solution, but without luck.
Could please somebody tell me, how to solve this issue?
Here is onActivityResultMethod:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
Log.i(GlobalApplication.APP_LOG_NAMESPACE, "Trying to process image");
GlobalApplication globalAppClass = ((GlobalApplication) getApplicationContext());
AppHelper helper = new AppHelper();
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Uri imageUri = data.getData();
if(imageUri == null) {
Log.i(GlobalApplication.APP_LOG_NAMESPACE, "Image URI is null");
}
Bitmap bitmap;
Bitmap resizedBitmap;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "DAMAGE_" + globalAppClass.getEanCode() + "_" + timeStamp + ".jpg";
String dirname = "smartt/"+globalAppClass.getEanCode();
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
resizedBitmap = helper.getResizedBitmap(bitmap, 768, 1024);
helper.createDirectoryAndSaveImage(resizedBitmap, imageFileName, dirname);
// place thumbnail into image view
//mImageView.setImageBitmap(imageBitmap);
TextView photoCountTv = (TextView)findViewById(R.id.damageReportTakenPhotosCountTv);
photoCountTv.setText(R.string.foto_attached);
photoCountTv.setTextColor(getResources().getColor(R.color.green));
TextView dataPassingTv = (TextView)findViewById(R.id.damageReportPassingTitle);
dataPassingTv.setText(R.string.data_passing);
dataPassingTv.setTextColor(getResources().getColor(R.color.green));
} catch (FileNotFoundException e) {
Log.e(GlobalApplication.APP_LOG_NAMESPACE, "onActivityResult method cannot be processed, file not found", e);
e.printStackTrace();
} catch (IOException e) {
Log.e(GlobalApplication.APP_LOG_NAMESPACE, "onActivityResult method cannot be processed, IOE Exception", e);
e.printStackTrace();
} catch (Exception e) {
Log.e(GlobalApplication.APP_LOG_NAMESPACE, "onActivityResult method cannot be processed, Exception", e);
e.printStackTrace();
}
}
}
Thanks for any advice
i know this question is older, but i think many people have a problem with that. As #CommonsWare stated out you have to provide your own URI like this:
photoFile = getOutputMediaFile();
// Continue only if the File was successfully created
if (photoFile != null) {
String fileName = photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
with a file like this:
public File getOutputMediaFile() {
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"Shaufel");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
// base.saveValidationError("MyCameraApp: failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp
+ ".jpg");
return mediaFile;
}
just safe in your application the fileName (perhaps also onSaveInstanceState())
in onActivityResult i load the bitmap like this
public Bitmap decodeSampledBitmapFromResource(Resources res, File file, int reqWidth,
int reqHeight) throws IOException {
FileInputStream ino = new FileInputStream(new File(fileName));
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(ino.getFD(), null, options);
ino.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(fileName, options);
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
this.reqHeight = reqHeight;
this.reqWidth = reqWidth;
// Raw height and width of image
this.height = options.outHeight;
this.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;
}

ImageView setImageBitmap not working on certain devices

I was practicing around with the Camera API for which I did the following:
a. Setup a directory for the image captured (for startActivityForResult)
b. Setup the Bitmap so that the image could be shown once saved in the app itself.
Here's the code for the following:
Setting up the directory.
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(IMAGE_DIRECTORY_NAME, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
Global variables in the application
// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
public static final int MEDIA_TYPE_IMAGE = 1;
// directory name to store the captured images
private static final String IMAGE_DIRECTORY_NAME = "my_camera_app";
private Uri fileUri;
// Views
ImageView photo;
Button camera;
Camera implementation logic
// Use camera function
private void captureImage() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Successfully captured the image
// display in imageview
previewImage();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
private void previewImage() {
try {
// Bitmap factory
BitmapFactory.Options options = new BitmapFactory.Options();
// Downsizing image as it throws OutOfMemory exception for larger
// images
options.inSampleSize = 3;
final Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
photo.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
The problem I am having is that ... for some of the devices that I tested the app, the app shows a blank preview of the image shot while in others the app works completely well.
Why am I getting a blank feedback ? and in some of the cases, when an image is saved, the user is not directed to my app, instead the user is stuck in the camera app.
Please do help.
I had the same problem and solved it by changing the rendering of the view to software
ImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
At least for Kitkat 4.4.2 on a Galaxy S4, with a relative layout, I had to call invalidate() on the ImageView that i just setImageBitmap on. If i didn't, i got the blank screen. After adding the invalidate() after setImageBitmap(), then I got the image.
try loading bitmap efficiently:
public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
//BitmapFactory.Options optionss = new BitmapFactory.Options();
//optionss.inPreferredConfig = Bitmap.Config.RGB_565;
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
BitmapFactory.decodeFile(path,options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, 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;}
Actually it is setting but it doesnt appear for some reason.
profileImageView.post(new Runnable() {
#Override
public void run() {
profileImageView.setImageBitmap(bm);
}
});
This works for me.
One way I got around this problem was when setting the FileUri, I stored the Uri using SharedPreferences. So in my code:
public void takePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = FileHelper.getOutputMediaFileUri();
// Store uri to SharedPreferences
pref.setImageUri(fileUri.toString());
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
In my onActivityResult callback:
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {
// If user is taking photo then only call the SharedPreferences
// If user is selecting photo from gallery, we can use the Intent data
fileUri = Uri.parse(pref.getImageUri());
if (fileUri.getPath().toString().length() < 1) {
Toast.makeText(getApplicationContext(),
"Sorry something went wrong ... Please try again",
Toast.LENGTH_LONG).show();
} else {
String path = fileUri.getPath().toString();
db_img_path = path;
imageholder.setVisibility(View.VISIBLE);
Bitmap bitmap = PathtoImage.previewImage(path);
imagepreview.setImageBitmap(bitmap);
}
}
Bonus :)
In my previewImage method, I have made adjustments for orientation, the code looks like this :
public static Bitmap previewImage(String path) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
final Bitmap bitmap = BitmapFactory.decodeFile(path, options);
// Providing adjustment so that the image is shown in the correct orientation
Matrix adjustment = adjustOrientation(path);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), adjustment, true);
return resizedBitmap;
}
In this method I call another method adjustOrientation which gives me the Matrix fix to the image.
// Adjustment for orientation of images
public static Matrix adjustOrientation(String path) {
Matrix matrix = new Matrix();
try {
ExifInterface exifReader = new ExifInterface(path);
int orientation = exifReader.getAttributeInt(
ExifInterface.TAG_ORIENTATION, -1);
if (orientation == ExifInterface.ORIENTATION_NORMAL) {
// do nothing
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
matrix.postRotate(90);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
matrix.postRotate(180);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
matrix.postRotate(270);
}
} catch (IOException e) {
e.printStackTrace();
}
return matrix;
}
This is my implementation for the issue, if anyone has a better implementation to this, please do post :)
In my case, it's fixed by adding android:layerType="software" in XML.
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layerType="software"
android:src="#drawable/placeholder"/>
Hopefully this will help you too!

Make a screenshot code support multiple screen sizes

I have a class where i take the screenshot of the layout and store it as a JPEG file....the problem i am having is the image size varies with the screen resolution.... for eg. if i use medium resolution phones the image size is around 50-60kb but for high resolution it goes upto 1.5mbs....so is there any way i can keep the image size constant independent of screen size or resolution???
public class abc extends Activity {
View content;
String fileName, fname;
static File file;
static String RECE;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.rece);
ImageView iv = (ImageView) findViewById(R.id.Ivsignature);
iv.setImageBitmap(Signature.sign);
Initialize();
content = findViewById(R.id.Rlrece);
ViewTreeObserver vto = content.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#SuppressWarnings("deprecation")
public void onGlobalLayout() {
content.getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
getScreen();
}
});
}
private void getScreen() {
View view = content;
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String myPath = Environment.getExternalStorageDirectory() + "/Rece";
File myDir = new File(myPath);
try {
myDir.mkdirs();
} catch (Exception e) {
}
fname = fileName + ".jpg";
file = new File(myDir, fname);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
b.compress(CompressFormat.JPEG, 100, fos);
// Toast.makeText(getApplicationContext(), fname + " saved",
// Toast.LENGTH_LONG).show();
Intent my = new Intent(getApplicationContext(),
DialogActivity.class);
my.putExtra("Rsystrace", DialogActivity.Systrace);
startActivityForResult(my, 1);
} catch (Throwable ex) {
Toast.makeText(getApplicationContext(),
"error: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
When you do screenshot you'll ofcourse have screen size dependent image (the resolution of the image is different because screens are different).
You can compress or resize you bitmap as you want and after resize to the fixed size - the file size will be fixed.
PS. I suggest you to use PNG except of JPEG.
You can create a object BitmapFactory.Options() and set the property inSampleSize given a scale factor (you will need to calculate this).
Than you can use like in BitmapFactory.decodeFile() to take a image at the size you want (based on inSampleSize).
-- EDIT --
Example using a image in a disk at "photoPath":
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
BitmapFactory.decodeFile(photoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
int scaleFactor = Math.min(newWidth/width, newHeigth/heigth);
bmOptions.inSampleSize = scaleFactor;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, bmOptions);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
FileOutputStream fos;
fos = new FileOutputStream(photoPath);
fos.write(bytes.toByteArray());
fos.close();

Categories

Resources