Skip to content

Instantly share code, notes, and snippets.

@rafsanahmad
Created November 11, 2021 08:35
Show Gist options
  • Save rafsanahmad/d4f45046cf8a51fdf9e49c5b5d68dc87 to your computer and use it in GitHub Desktop.
Save rafsanahmad/d4f45046cf8a51fdf9e49c5b5d68dc87 to your computer and use it in GitHub Desktop.
Image video Utility functions like handle rotation, resize, save bitmap, get size, metadata etc.
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.ColorStateList;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.PorterDuff;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class ImageUtils {
static AlertDialog.Builder builder;
public static Bitmap resize(Bitmap image, int maxWidth, int maxHeight) {
if (maxHeight > 0 && maxWidth > 0) {
int width = image.getWidth();
int height = image.getHeight();
float ratioBitmap = (float) width / (float) height;
float ratioMax = (float) maxWidth / (float) maxHeight;
int finalWidth = maxWidth;
int finalHeight = maxHeight;
if (ratioMax > ratioBitmap) {
finalWidth = (int) ((float) maxHeight * ratioBitmap);
} else {
finalHeight = (int) ((float) maxWidth / ratioBitmap);
}
image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
return image;
} else {
return image;
}
}
public static int getVideoMetadata(Context context, Uri fileURL) {
try {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(context, fileURL);
String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
Log.v("DIMENSION", "H: " + height + " W: " + width);
return Integer.parseInt(height);
} catch (Exception e) {
return 0;
}
}
public static int getVideoDuration(Context context, Uri fileURL) {
try {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(context, fileURL);
String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
Log.v("Duration", "H: " + height);
return Integer.parseInt(height);
} catch (Exception e) {
return 0;
}
}
public static int getVideoWidth(Context context, Uri fileURL) {
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(context, fileURL);
String height = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
String width = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
Log.v("DIMENSION", "H: " + height + " W: " + width);
return Integer.parseInt(width);
}
public static String getPath(Context context, Uri uri) {
String path = null;
String[] projection = {MediaStore.Video.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor == null) {
path = uri.getPath();
} else {
cursor.moveToFirst();
int column_index = cursor.getColumnIndexOrThrow(projection[0]);
path = cursor.getString(column_index);
cursor.close();
}
return ((path == null || path.isEmpty()) ? (uri.getPath()) : path);
}
public static File saveBitmap(Context context, String filename, Bitmap bitmap) {
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + File.separator + filename + ".png");
OutputStream outStream = null;
//File file = new File(filename + ".png");
if (file.exists()) {
file.delete();
file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS) + File.separator + filename + ".png");
Log.e("file exist", "" + file + ",Bitmap= " + filename);
}
try {
// make a new bitmap from your file
//Bitmap bitmap = BitmapFactory.decodeFile(file.getName());
outStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Log.e("file", "" + file);
return file;
}
public static Bitmap handleSamplingAndRotationBitmap(Context context, Uri selectedImage)
throws IOException {
int MAX_HEIGHT = 1024;
int MAX_WIDTH = 1024;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
InputStream imageStream = context.getContentResolver().openInputStream(selectedImage);
BitmapFactory.decodeStream(imageStream, null, options);
imageStream.close();
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, MAX_WIDTH, MAX_HEIGHT);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
imageStream = context.getContentResolver().openInputStream(selectedImage);
Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);
img = rotateImageIfRequired(context, img, selectedImage);
return img;
}
private 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);
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
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++;
}
}
return inSampleSize;
}
private static Bitmap rotateImageIfRequired(Context context, Bitmap img, Uri selectedImage) throws IOException {
InputStream input = context.getContentResolver().openInputStream(selectedImage);
ExifInterface ei;
if (Build.VERSION.SDK_INT > 23)
ei = new ExifInterface(input);
else
ei = new ExifInterface(selectedImage.getPath());
int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
return rotateImage(img, 90);
case ExifInterface.ORIENTATION_ROTATE_180:
return rotateImage(img, 180);
case ExifInterface.ORIENTATION_ROTATE_270:
return rotateImage(img, 270);
default:
return img;
}
}
private static Bitmap rotateImage(Bitmap img, int degree) {
Matrix matrix = new Matrix();
matrix.postRotate(degree);
Bitmap rotatedImg = Bitmap.createBitmap(img, 0, 0, img.getWidth(), img.getHeight(), matrix, true);
img.recycle();
return rotatedImg;
}
public static String checkOrientation(Bitmap bitmap) {
if (bitmap.getHeight() > bitmap.getWidth()) {
return "P";
} else {
return "L";
}
}
public static void setGradients(String firstColor, String secondColor, GradientDrawable.Orientation orientation, View view) {
GradientDrawable gd = new GradientDrawable(
orientation,
new int[]{Color.parseColor(firstColor), Color.parseColor(secondColor)});
gd.setCornerRadius(0f);
gd.setGradientCenter(0.75f, 0.0f);
view.setBackground(gd);
}
public static Bitmap getThumbnail(ContentResolver cr, String path) throws Exception {
Cursor ca = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.MediaColumns._ID}, MediaStore.MediaColumns.DATA + "=?", new String[]{path}, null);
if (ca != null && ca.moveToFirst()) {
int id = ca.getInt(ca.getColumnIndex(MediaStore.MediaColumns._ID));
ca.close();
return MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MICRO_KIND, null);
}
ca.close();
return null;
}
public static float getFileSize(Context context, Uri uri) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor != null) {
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
cursor.moveToFirst();
float fileSize = cursor.getLong(sizeIndex);
cursor.close();
return fileSize; // returns size in bytes
}
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment