How do I make the image scaled efficiency? - android

In my app, I have built a camera function in the Activity B. The selected image will then placed in the imageView B.
Activity B ---> one imageView B, used to place the selected image
The selected image can be displayed on ImageView B, but it looked blur. Please tell me what should I do . Thanks in advance !
Activity B
private void activeGallery() {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_LOAD_IMAGE:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap a = (BitmapFactory.decodeFile(picturePath));
photo=scaleBitmap(a,200,200);
imageView.setImageBitmap(photo);
}
}
}
public static Bitmap scaleBitmap(Bitmap bitmap, int wantedWidth, int wantedHeight) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
float scaleWidth = ((float) wantedWidth) / width;
float scaleHeight = ((float) wantedHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, wantedWidth, wantedHeight, false);
return resizedBitmap;
}
Original image
Place in ImageView B (looked blur)

how can I fix the size of the imageView ?
You may try this
<ImageView
android:id="#+id/YourImageViewId"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentRight="true"
android:scaleType="centerInside"
android:gravity="right|center_vertical"
android:padding="10px"
/>
Source get from here

Related

How to delete an image from device in Android programmatically?

I am creating an app that lets user select an image from gallery and store it in my DB.
I am successful in doing that.
Now I want that selected image to be deleted from phone storage also.
how do I do it then?
I might even want to restore it later in users gallery.
This is what I do to get image from gallery.
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
switch (requestCode)
{
case 42:
if (resultCode == RESULT_OK)
{
Uri uri = data.getData();
InputStream inputStream = null;
try
{
inputStream = getBaseContext().getContentResolver().openInputStream(uri);
Bitmap bm = BitmapFactory.decodeStream(inputStream);
int maxHeight = 1920;
int maxWidth = 1920;
float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
saveImageToInternalStorage(bitmap, getFileName(uri));
bm.recycle();
bitmap.recycle();
finishActivity(42);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
}
This is the Uri path I'm getting
content://com.android.providers.media.documents/document/image%3A5857
my onActivityResult looks like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
switch (requestCode)
{
case 42:
if (resultCode == RESULT_OK)
{
Uri uri = data.getData();
InputStream inputStream = null;
try
{
inputStream = getBaseContext().getContentResolver().openInputStream(uri);
Bitmap bm = BitmapFactory.decodeStream(inputStream);
int maxHeight = 1920;
int maxWidth = 1920;
float scale = Math.min(((float) maxHeight / bm.getWidth()), ((float) maxWidth / bm.getHeight()));
Matrix matrix = new Matrix();
matrix.postScale(scale, scale);
Bitmap bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
saveImageToInternalStorage(bitmap, getFileName(uri));
bm.recycle();
bitmap.recycle();
finishActivity(42);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
}
Are you asking about this same question Delete image file from device programmatically Maybe you can get a solution from there.
try this
public static boolean delete(final Context context, final File file) {
final String where = MediaStore.MediaColumns.DATA + "=?";
final String[] selectionArgs = new String[] {
file.getAbsolutePath()
};
final ContentResolver contentResolver = context.getContentResolver();
final Uri filesUri = MediaStore.Files.getContentUri("external");
contentResolver.delete(filesUri, where, selectionArgs);
if (file.exists()) {
contentResolver.delete(filesUri, where, selectionArgs);
}
return !file.exists();
}

just a part of base64 decoded image is displaying

I want to post a bitmap to server by decoding base64. But after decoding I can display just a part of image(some top of image). How can I solve this problem?
I won't write codes for posting because they are work succesfully. In bitmapToString function I can get base64 strings and I try to display them, but I can see only a part of images.
Codes:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==GALLERY_REQUEST) && resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
Bitmap bitmap = scaleBitmap(BitmapFactory.decodeFile(filePath), 512,512,360);
bitMapToString(bitmap); //this function logs the base64 strings
}
}
}
public String bitmapToString(Bitmap bitmap){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String result = Base64.encodeToString(imageBytes, Base64.DEFAULT);
Log.d("BitmapToString",result); //here I get base64 strings
return result;
}
public Bitmap scaleBitmap(Bitmap bm, int maxWidth, int maxHeight, int ifSquareMaxValue) {
int width = bm.getWidth();
int height = bm.getHeight();
if(maxWidth>width && maxHeight>height)
return bm;
if (width > height) {
float ratio = (float) width / maxHeight;
width = maxHeight;
height = (int)(height / ratio);
} else if (height > width) {
float ratio = (float) height / maxWidth;
height = maxWidth;
width = (int)(width / ratio);
} else {
height = ifSquareMaxValue;
width = ifSquareMaxValue;
}
return Bitmap.createScaledBitmap(bm, width, height, true);
}
for example, a base64 string of an image is this: (from bitmapToString function line: Log.d("BitmapToString",result);)
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQE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Nm1dkf+f5j1Pp/PkkEk/H+fv6A+n6j0NfX3wU/YZ/aV+P8lsvws8EHXTd7PI/0iSPeHL4GFtZcZ2N+Wc9Sf2z/AGUv+DeH9prxzqcD/GT4ZXOk6XM8J86Ge4nPlkShztEdn0ZRkbucjnIzXnZzxzwvkVOtPHZthFOgr1MNSr0p4pWbTXsfaKV9NvXVtO/RClUqO0ISl0uk7fa3ey+G/wA11ufzMQWk106xW4Msjnakaj5mb5uBk4z8vr36k4z6PoPwT+LHijZ/wj/gfWNU342fZ1tfm64x5lynXHf2655/0Tvgf/wa1fsWW1hZar4/vNasNWhhim8n+y7mUGcl1cEnxNF0Ukg7MHBGOHNfqB8J/wDgij+xl8IRAPDs89ybbZs+0aICCU3jnfrc5/PuRzkHP4dnv0pfD/LI1aeCxlKtXp+7KljpLDNyTmuWK9tzPRdm229bu51QwFZ6TlSjtq5pPeS1Tej0Xfpp/N/lk6Z+xR+1nqqq2m/AvxfeK2NpiTSsEfNjhtRHoeR755OT1dt/wT1/bdutph/Zw8cyKccqmi9Mtzzq3ov/AOsnFf6/fhP9lb4R+CoY49F0jTLgRAbDLo1mPukgE7nl69ec/wAsewWPhHR9Lj8uz8L6CwQAAtpGncDc2M5tG/2+vTPUgc/mOI+mbgqc5xocNU8VCK0qYeeLqxau0neEnfbXotNbvXVYCCupVJX0s6cVJatq++u2nR+69Fdy/wAb1v8Agm9+28sRcfs4+OyQoIBXRs53Ec51fH5nkHGeAaw
when I use use in img tag display like this:
http://kombers.org/a.html

How can I set the size of Image when imported in Android?

I am using the following code to let a user import an image from their gallery into the app.
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
But, I want the size of the image to be a certain size no matter what the image size they have imported is. Whenever I import an image it always fill the whole screen. Let's say I want the image size to be 50 width by 50 height.
There are two ways to set the imageview size
from the xml
<ImageView
android:id="#+id/image_view"
android:layout_width="200dp"
android:layout_height="100dp"
android:scaleType="fitCenter"
android:src="#drawable/iclauncher"
android:scaleType="fitXY"/>
from programmatically
image_view.getLayoutParams().height = 20;
image_view.getLayoutParams().width = 20;
this is the way to resize bitmap image
public Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(
bm, 0, 0, width, height, matrix, false);
bm.recycle();
return resizedBitmap;
}
As suggested by saeed:
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(decodeUri(this, Uri.parse(imgDecodableString), 50));
Where decodeUri is from here.

Android resize gallery image

When I pick an image from the gallery it is too large and I need to resize it. Can anyone give me suggestions on how I might be able to accomplish this?
See code below:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = Media.getBitmap(this.getContentResolver(), uri);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
imageView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_GALLERY);
imageView.setImageBitmap(bitmap);
}
});
This post has some excellent samples for you: How to Resize a Bitmap in Android?
In your case, this method helps
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// CREATE A MATRIX FOR THE MANIPULATION
Matrix matrix = new Matrix();
// RESIZE THE BIT MAP
matrix.postScale(scaleWidth, scaleHeight);
// "RECREATE" THE NEW BITMAP
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
Edit
Also from the same post, this fits your need in an easier way
Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, false);
Update
You can use the code in this way:
// Set the new width and height you want
int newWidth;
int newHeight;
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_GALLERY && resultCode == RESULT_OK) {
Uri uri = data.getData();
try {
bitmap = Media.getBitmap(this.getContentResolver(), uri);
bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Image blur in android

I have taken thumbnail image from gallery which is smaller in size and resized into 300*300 size.
By doing that the image looking so blurred.
getting image from gallery
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 0:
if (resultCode == RESULT_OK) {
try {
flag = 1;
Uri selectedImage = imageReturnedIntent.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex); // file
// path
// of
// selected
// image
cursor.close();
// Convert file path into bitmap image using below line.
yourSelectedImage = download.getResizedBitmap(
image.decodeImage(filePath),270,228);
// put bitmapimage in your imageview
profile_image.setImageBitmap(
yourSelectedImage);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Image resizing
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
{
try
{
if(bm!=null)
{
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// create a matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// recreate the new Bitmap
resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return resizedBitmap;
}
Images get blurred when you enlarge them (unless you are using an vector image and you are using a bitmap). Your getResizedBitmap method doesn't do anything much other than stretching the image to fit the new size. The only way you are going to solve your problem is by selecting larger images (but then eventually you will run into the aspect ratio problem, so you should really rethink your scaling algorithm).
Of course enlarging a bitmap image will be pixelated..

Categories

Resources