Example usage for android.graphics Bitmap createScaledBitmap

List of usage examples for android.graphics Bitmap createScaledBitmap

Introduction

In this page you can find the example usage for android.graphics Bitmap createScaledBitmap.

Prototype

public static Bitmap createScaledBitmap(@NonNull Bitmap src, int dstWidth, int dstHeight, boolean filter) 

Source Link

Document

Creates a new bitmap, scaled from an existing bitmap, when possible.

Usage

From source file:Main.java

public static Bitmap getScaleBitmap(Bitmap bitmap, float srcW, float srcH, float destW, float destH) {
    Bitmap bmp = null;//from ww w.j a  va  2  s .  c om
    float orgW = 0;
    float orgH = 0;

    if (srcW <= destW && srcH <= destH) {
        return bitmap;
    }

    if ((srcW / srcH) > (destW / destH)) {
        orgW = destW;
        orgH = (orgW * srcH) / srcW;
    } else {
        orgH = destH;
        orgW = (orgH * srcW) / srcH;
    }

    bmp = Bitmap.createScaledBitmap(bitmap, (int) orgW, (int) orgH, false);
    return bmp;
}

From source file:com.nextgis.maplibui.util.NotificationHelper.java

public static Bitmap getLargeIcon(int iconResourceId, Resources resources) {
    Bitmap icon = BitmapFactory.decodeResource(resources, iconResourceId);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
        return icon;

    int iconSize = ControlHelper.dpToPx(40, resources);
    int innerIconSize = ControlHelper.dpToPx(24, resources);
    icon = Bitmap.createScaledBitmap(icon, iconSize, iconSize, false);
    Bitmap largeIcon = icon.copy(Bitmap.Config.ARGB_8888, true);
    icon = Bitmap.createScaledBitmap(icon, innerIconSize, innerIconSize, false);

    Canvas canvas = new Canvas(largeIcon);
    int center = canvas.getHeight() / 2;
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    paint.setColor(resources.getColor(R.color.accent));
    canvas.drawCircle(center, center, center, paint);
    paint.setColor(Color.WHITE);//from   w w  w.ja  v  a  2 s .c o  m
    canvas.drawBitmap(icon, center - icon.getWidth() / 2, center - icon.getWidth() / 2, paint);

    return largeIcon;
}

From source file:Main.java

/**
 * Resize a bitmap object to fit the passed width and height
 *
 * @param input//w  w w  . j a va 2 s . c o m
 *           The bitmap to be resized
 * @param destWidth
 *           Desired maximum width of the result bitmap
 * @param destHeight
 *           Desired maximum height of the result bitmap
 * @return A new resized bitmap
 * @throws OutOfMemoryError
 *            if the operation exceeds the available vm memory
 */
public static Bitmap resizeBitmap(final Bitmap input, int destWidth, int destHeight, int rotation)
        throws OutOfMemoryError {

    int dstWidth = destWidth;
    int dstHeight = destHeight;
    final int srcWidth = input.getWidth();
    final int srcHeight = input.getHeight();

    if (rotation == 90 || rotation == 270) {
        dstWidth = destHeight;
        dstHeight = destWidth;
    }

    boolean needsResize = false;
    float p;
    if ((srcWidth > dstWidth) || (srcHeight > dstHeight)) {
        needsResize = true;
        if ((srcWidth > srcHeight) && (srcWidth > dstWidth)) {
            p = (float) dstWidth / (float) srcWidth;
            dstHeight = (int) (srcHeight * p);
        } else {
            p = (float) dstHeight / (float) srcHeight;
            dstWidth = (int) (srcWidth * p);
        }
    } else {
        dstWidth = srcWidth;
        dstHeight = srcHeight;
    }

    if (needsResize || rotation != 0) {
        Bitmap output;

        if (rotation == 0) {
            output = Bitmap.createScaledBitmap(input, dstWidth, dstHeight, true);
        } else {
            Matrix matrix = new Matrix();
            matrix.postScale((float) dstWidth / srcWidth, (float) dstHeight / srcHeight);
            matrix.postRotate(rotation);
            output = Bitmap.createBitmap(input, 0, 0, srcWidth, srcHeight, matrix, true);
        }
        return output;
    } else
        return input;
}

From source file:Main.java

public static Bitmap scaleDownBitmap(Context context, Bitmap bitmap, int width) {
    if (bitmap != null) {

        try {//from w  w w  .j  a  va 2 s.c  o  m
            final float densityMultiplier = context.getResources().getDisplayMetrics().density;
            int bitmapHeight = bitmap.getHeight();
            int bitmapWidth = bitmap.getWidth();
            int w, h, x, y;
            if (bitmapHeight > (bitmapWidth * 3) / 4) {
                w = bitmapWidth;
                h = (bitmapWidth * 3) / 4;
                x = 0;
                y = (bitmapHeight - h) / 2;
            } else if (bitmapWidth > (bitmapHeight * 4) / 3) {
                h = bitmapHeight;
                w = (bitmapHeight * 4) / 3;
                y = 0;
                x = (bitmapWidth - w) / 2;
            } else {
                w = bitmapWidth;
                h = bitmapHeight;
                x = 0;
                y = 0;
            }

            bitmap = Bitmap.createBitmap(bitmap, x, y, w, h);
            int dstWidth = (int) (width * densityMultiplier);
            int dstHeight = (dstWidth * 3) / 4;
            if (w > dstWidth || h > dstHeight) {
                bitmap = Bitmap.createScaledBitmap(bitmap, dstWidth, dstHeight, false);
            }
        } catch (Exception ex) {
            //under some situation the the value of h becomes <= zero in createbitmap, adding a try catch and returning the original bitmap
            return bitmap;
        }
    }
    return bitmap;
}

From source file:Main.java

public static Bitmap getArtworkQuick(Context context, long album_id, int w, int h) {
    // NOTE: There is in fact a 1 pixel border on the right side in the
    // ImageView/*ww  w  .j  a v  a2s .  co m*/
    // used to display this drawable. Take it into account now, so we don't
    // have to
    // scale later.
    w -= 1;
    ContentResolver res = context.getContentResolver();
    Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
    if (uri != null) {
        ParcelFileDescriptor fd = null;
        try {
            fd = res.openFileDescriptor(uri, "r");
            int sampleSize = 1;

            // Compute the closest power-of-two scale factor
            // and pass that to sBitmapOptionsCache.inSampleSize, which will
            // result in faster decoding and better quality
            sBitmapOptionsCache.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache);
            int nextWidth = sBitmapOptionsCache.outWidth >> 1;
            int nextHeight = sBitmapOptionsCache.outHeight >> 1;
            while (nextWidth > w && nextHeight > h) {
                sampleSize <<= 1;
                nextWidth >>= 1;
                nextHeight >>= 1;
            }

            sBitmapOptionsCache.inSampleSize = sampleSize;
            sBitmapOptionsCache.inJustDecodeBounds = false;
            Bitmap b = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache);

            if (b != null) {
                // finally rescale to exactly the size we need
                if (sBitmapOptionsCache.outWidth != w || sBitmapOptionsCache.outHeight != h) {
                    Bitmap tmp = Bitmap.createScaledBitmap(b, w, h, true);
                    // Bitmap.createScaledBitmap() can return the same
                    // bitmap
                    if (tmp != b)
                        b.recycle();
                    b = tmp;
                }
            }

            return b;
        } catch (FileNotFoundException e) {
        } finally {
            try {
                if (fd != null)
                    fd.close();
            } catch (IOException e) {
            }
        }
    }
    return null;
}

From source file:Main.java

@SuppressLint("NewApi")
public static Bitmap createVideoThumbnail(String filePath, int kind) {
    Bitmap bitmap = null;//from  w  w  w .j a v a  2 s . c om
    if (Build.VERSION.SDK_INT < 10) {
        // This peace of code is for compatibility with android 8 and 9.
        return android.media.ThumbnailUtils.createVideoThumbnail(filePath, kind);
    }

    // MediaMetadataRetriever is not available for Android version less than 10
    // but we need to use it in order to get first frame of the video for thumbnail.
    MediaMetadataRetriever retriever = new MediaMetadataRetriever();

    try {
        retriever.setDataSource(filePath);
        bitmap = retriever.getFrameAtTime(0);
    } catch (IllegalArgumentException ex) {
        // Assume this is a corrupt video file
    } catch (RuntimeException ex) {
        // Assume this is a corrupt video file.
    } finally {
        try {
            retriever.release();
        } catch (RuntimeException ex) {
            // Ignore failures while cleaning up.
            Log.w("ThumbnailUtils", "MediaMetadataRetriever failed with exception: " + ex);
        }
    }

    if (bitmap == null)
        return null;

    if (kind == Images.Thumbnails.MINI_KIND) {
        // Scale down the bitmap if it's too large.
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int max = Math.max(width, height);
        if (max > 512) {
            float scale = 512f / max;
            int w = Math.round(scale * width);
            int h = Math.round(scale * height);
            bitmap = Bitmap.createScaledBitmap(bitmap, w, h, true);
        }
    } else if (kind == Images.Thumbnails.MICRO_KIND) {

        bitmap = android.media.ThumbnailUtils.extractThumbnail(bitmap, TARGET_SIZE_MICRO_THUMBNAIL,
                TARGET_SIZE_MICRO_THUMBNAIL, OPTIONS_RECYCLE_INPUT);
    }

    return bitmap;
}

From source file:com.andreadec.musicplayer.ImageLoaderTask.java

@Override
protected Bitmap doInBackground(Void... params) {
    Bitmap originalImage = item.getImage();
    if (originalImage == null)
        return null;
    Bitmap image = Bitmap.createScaledBitmap(originalImage, listImageSize, listImageSize, true);
    synchronized (imagesCache) {
        imagesCache.put(item.getPlayableUri(), image);
    }/* w  w w  .  j a va  2s.  c o  m*/
    originalImage = null;
    return image;
}

From source file:Main.java

public static Bitmap scaleBitmap(Bitmap src, int maxWidth, int maxHeight) {
    double scaleFactor = Math.min(((double) maxWidth) / src.getWidth(), ((double) maxHeight) / src.getHeight());
    return Bitmap.createScaledBitmap(src, (int) (src.getWidth() * scaleFactor),
            (int) (src.getHeight() * scaleFactor), false);
}

From source file:Main.java

private static Bitmap processBitmap(Bitmap bm) {

    float width = bm.getWidth();
    float height = bm.getHeight();
    int maxWidth = 150;
    int maxHeight = 150;
    float oldHeight;
    int oldWidth;
    float newWidth;
    float newHeight;
    float schnitt;

    Log.i("==============>", "width: " + width);
    Log.i("==============>", "height: " + height);

    newWidth = maxWidth;/*w w  w  . ja  v a  2 s.  com*/
    schnitt = newWidth / width;
    newHeight = (int) (schnitt * height);

    if (newHeight > maxHeight) {
        oldHeight = newHeight;
        oldWidth = (int) newWidth;
        newHeight = maxHeight;
        schnitt = newHeight / oldHeight;
        newWidth = schnitt * oldWidth;
    }

    Log.i("==============>", "New Width: " + newWidth);
    Log.i("==============>", "New Height: " + newHeight);

    bm = Bitmap.createScaledBitmap(bm, (int) newWidth, (int) newHeight, true);
    Log.i(I, "create scaled Bitmap successful");

    return bm;
}

From source file:Main.java

public static Bitmap getImageBitmapFromAssetsFolderThroughImagePathName(Context context, String imagePathName,
        int reqWidth, int reqHeight) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;/* w ww.j  a v  a 2s. c o  m*/
    Bitmap bitmap = null;
    AssetManager assetManager = context.getResources().getAssets();
    InputStream inputStream = null;

    try {
        inputStream = assetManager.open(imagePathName);
        inputStream.mark(Integer.MAX_VALUE);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        System.gc();
        return null;
    }

    try {
        if (inputStream != null) {
            BitmapFactory.decodeStream(inputStream, null, opts);
            inputStream.reset();
        } else {
            return null;
        }
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        System.gc();
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    opts.inSampleSize = calculateInSampleSiez(opts, reqWidth, reqHeight);
    //         Log.d(TAG,""+opts.inSampleSize);
    opts.inJustDecodeBounds = false;
    opts.inPreferredConfig = Bitmap.Config.RGB_565;
    opts.inPurgeable = true;
    opts.inInputShareable = true;
    opts.inDither = false;
    opts.inTempStorage = new byte[512 * 1024];
    try {
        if (inputStream != null) {
            bitmap = BitmapFactory.decodeStream(inputStream, null, opts);
        } else {
            return null;
        }
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        System.gc();
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }
    }
    //Log.d(TAG,"w:"+bitmap.getWidth()+" h:"+bitmap.getHeight());
    if (bitmap != null) {
        try {
            bitmap = Bitmap.createScaledBitmap(bitmap, reqWidth, reqHeight, true);
        } catch (OutOfMemoryError outOfMemoryError) {
            outOfMemoryError.printStackTrace();
            System.gc();
            return null;
        }
    }
    return bitmap;
}