Example usage for android.graphics Bitmap setDensity

List of usage examples for android.graphics Bitmap setDensity

Introduction

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

Prototype

public void setDensity(int density) 

Source Link

Document

Specifies the density for this bitmap.

Usage

From source file:Main.java

@SuppressWarnings("deprecation")
public static Drawable getDrawableFromFile(File pngFile, int density) {
    Bitmap bmp = BitmapFactory.decodeFile(pngFile.getPath());
    bmp.setDensity(density);

    return new BitmapDrawable(bmp);
}

From source file:Main.java

public static Bitmap flipBitmap(Bitmap src) {
    Matrix m = new Matrix();
    m.preScale(-1, 1);// www. j a v  a  2  s  . c o  m
    Bitmap dst = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, false);
    dst.setDensity(DisplayMetrics.DENSITY_DEFAULT);
    return dst;
}

From source file:Main.java

public static Drawable getDrawableFromFile(Context context, File pngFile, int density) {
    Bitmap bmp = BitmapFactory.decodeFile(pngFile.getPath());
    if (bmp != null)
        bmp.setDensity(density);

    return new BitmapDrawable(context.getResources(), bmp);
}

From source file:Main.java

public static Bitmap getBitmapForDensity(Resources res, int displayDpi, int resId) {
    try {//w ww. ja  v a2  s.  c o  m
        TypedValue value = new TypedValue();
        res.getValueForDensity(resId, displayDpi, value, true);
        AssetFileDescriptor fd = res.getAssets().openNonAssetFd(value.assetCookie, value.string.toString());
        Options opt = new Options();
        opt.inTargetDensity = displayDpi;
        Bitmap bitmap = BitmapFactory.decodeResourceStream(res, value, fd.createInputStream(), null, opt);
        bitmap.setDensity(res.getDisplayMetrics().densityDpi);
        fd.close();
        return bitmap;
    } catch (Exception e) {
        return BitmapFactory.decodeResource(res, resId);
    }
}

From source file:Main.java

/**
 * Get a mirror Bitmap/*from  ww w.ja  va2 s.c  o  m*/
 *
 * @param sourceBitmap Bitmap to Change
 * @return Mirror bitmap
 */
public static Bitmap getMirrorBitmap(Bitmap sourceBitmap) {
    Matrix m = new Matrix();
    m.preScale(-1, 1);
    Bitmap dst = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), m,
            false);
    dst.setDensity(DisplayMetrics.DENSITY_DEFAULT);
    return dst;
}

From source file:Main.java

public static BitmapDrawable getCachedIcon(Resources res, String packageName, int resId, Options opts) {
    int displayDpi = res.getDisplayMetrics().densityDpi;
    Bitmap bitmap = BitmapFactory.decodeFile(getCacheFilePath(packageName, resId), opts);
    if (bitmap == null) {
        return null;
    }//from   w  ww.j a v  a  2  s. c om
    bitmap.setDensity(displayDpi);
    return new BitmapDrawable(res, bitmap);
}

From source file:Main.java

/**
 * Get bitmap from a URI.// ww  w .  ja v  a  2s  .  c o  m
 *
 * @param context The context.
 * @param uriString The URI as a string.
 *
 * @return The bitmap.
 */
public static Bitmap getBitmapFromUri(final Context context, String uriString) {
    Bitmap bitmap = null;
    if (uriString == null) {
        return null;
    }

    Uri uri = Uri.parse(uriString);
    if (uri != null) {
        try {
            bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
            if (bitmap != null) {
                // We use default density for all bitmaps to avoid scaling.
                bitmap.setDensity(DisplayMetrics.DENSITY_DEFAULT);
            }
        } catch (IOException e) {

        }
    }
    return bitmap;
}

From source file:Main.java

/**
 * Creates a mutable bitmap from subset of source bitmap, transformed by the optional matrix.
 *//*w  w w.  ja  va2 s.c  om*/
private static Bitmap createBitmap(Bitmap source, int x, int y, int width, int height, Matrix m) {
    // Re-implement Bitmap createBitmap() to always return a mutable bitmap.
    Canvas canvas = new Canvas();

    Bitmap bitmap;
    Paint paint;
    if ((m == null) || m.isIdentity()) {
        bitmap = Bitmap.createBitmap(width, height, source.getConfig());
        paint = null;
    } else {
        RectF rect = new RectF(0, 0, width, height);
        m.mapRect(rect);
        bitmap = Bitmap.createBitmap(Math.round(rect.width()), Math.round(rect.height()), source.getConfig());

        canvas.translate(-rect.left, -rect.top);
        canvas.concat(m);

        paint = new Paint(Paint.FILTER_BITMAP_FLAG);
        if (!m.rectStaysRect()) {
            paint.setAntiAlias(true);
        }
    }
    bitmap.setDensity(source.getDensity());
    canvas.setBitmap(bitmap);

    Rect srcBounds = new Rect(x, y, x + width, y + height);
    RectF dstBounds = new RectF(0, 0, width, height);
    canvas.drawBitmap(source, srcBounds, dstBounds, paint);
    return bitmap;
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowser.java

/**
* This is a rather unintuitive helper method to load images. The reason why this method exists
* is because due to some service limitations, one may not be able to add images to native
* resource bundle. So this method offers a way to load image from www contents instead.
* However loading from native resource bundle is already preferred over loading from www. So
* if name is given, then it simply loads from resource bundle and the other two parameters are
* ignored. If name is not given, then altPath is assumed to be a file path _under_ www and
* altDensity is the desired density of the given image file, because without native resource
* bundle, we can't tell what density the image is supposed to be so it needs to be given
* explicitly./*from  w  ww.  ja v  a 2 s . c  o m*/
*/
private Drawable getImage(String name, String altPath, double altDensity) throws IOException {
    Drawable result = null;
    Resources activityRes = cordova.getActivity().getResources();

    if (name != null) {
        int id = activityRes.getIdentifier(name, "drawable", cordova.getActivity().getPackageName());
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            result = activityRes.getDrawable(id);
        } else {
            result = activityRes.getDrawable(id, cordova.getActivity().getTheme());
        }
    } else if (altPath != null) {
        File file = new File("www", altPath);
        InputStream is = null;
        try {
            is = cordova.getActivity().getAssets().open(file.getPath());
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            bitmap.setDensity((int) (DisplayMetrics.DENSITY_MEDIUM * altDensity));
            result = new BitmapDrawable(activityRes, bitmap);
        } finally {
            // Make sure we close this input stream to prevent resource leak.
            try {
                is.close();
            } catch (Exception e) {
            }
        }
    }
    return result;
}

From source file:org.appcelerator.titanium.view.TiDrawableReference.java

/**
 * Gets the bitmap, scaled to a width & height specified in TiDimension params.
 * @param destWidthDimension (null-ok) TiDimension specifying the desired width.  If .isUnitAuto()
 * then the width will be the source width.  If destWidthDimension is null, then the TiContext
 * will be used to determine the activity window's decor width and use that.
 * @param destHeightDimension (null-ok) TiDimension specifying the desired height.  If .isUnitAuto()
 * then the height will be the source height.  If destHeightDimension is null, then resulting height will
 * be at same ratio to the resulting width as the original height:width.
 * @return Bitmap, or null if any problem getting it.  Check logcat if null.
 *//*from  w  w  w.j  a  v a2  s  . c o  m*/
public Bitmap getBitmap(View parent, TiDimension destWidthDimension, TiDimension destHeightDimension) {
    int srcWidth, srcHeight, destWidth, destHeight;

    Bounds bounds = peekBounds();
    srcWidth = bounds.width;
    srcHeight = bounds.height;

    if (srcWidth <= 0 || srcHeight <= 0) {
        Log.w(TAG, "Bitmap bounds could not be determined. If bitmap is loaded, it won't be scaled.");
        return getBitmap(); // fallback
    }

    if (parent == null) {
        Activity activity = softActivity.get();
        if (activity != null && activity.getWindow() != null) {
            parent = activity.getWindow().getDecorView();
        }
    }

    Bounds destBounds = calcDestSize(srcWidth, srcHeight, destWidthDimension, destHeightDimension, parent);
    destWidth = destBounds.width;
    destHeight = destBounds.height;

    // If src and dest width/height are same, no need to go through all the sampling and scaling jazz.
    if (srcWidth == destWidth && srcHeight == destHeight) {
        return getBitmap();
    }

    if (destWidth <= 0 || destHeight <= 0) {
        // calcDestSize() should actually prevent this from happening, but just in case...
        Log.w(TAG, "Bitmap final bounds could not be determined.  If bitmap is loaded, it won't be scaled.");
        return getBitmap();
    }

    InputStream is = getInputStream();
    if (is == null) {
        Log.w(TAG, "Could not open stream to get bitmap");
        return null;
    }

    Bitmap b = null;
    try {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inInputShareable = true;
        opts.inPurgeable = true;
        opts.inSampleSize = calcSampleSize(srcWidth, srcHeight, destWidth, destHeight);
        if (Log.isDebugModeEnabled()) {
            StringBuilder sb = new StringBuilder();
            sb.append("Bitmap calcSampleSize results: inSampleSize=");
            sb.append(opts.inSampleSize);
            sb.append("; srcWidth=");
            sb.append(srcWidth);
            sb.append("; srcHeight=");
            sb.append(srcHeight);
            sb.append("; finalWidth=");
            sb.append(opts.outWidth);
            sb.append("; finalHeight=");
            sb.append(opts.outHeight);
            Log.d(TAG, sb.toString());
        }

        Bitmap bTemp = null;
        try {
            oomOccurred = false;
            bTemp = BitmapFactory.decodeStream(is, null, opts);
            if (bTemp == null) {
                Log.w(TAG, "Decoded bitmap is null");
                return null;
            }

            if (Log.isDebugModeEnabled()) {
                StringBuilder sb = new StringBuilder();
                sb.append("decodeStream resulting bitmap: .getWidth()=" + bTemp.getWidth());
                sb.append("; .getHeight()=" + bTemp.getHeight());
                sb.append("; getDensity()=" + bTemp.getDensity());
                Log.d(TAG, sb.toString());
            }

            // Set the bitmap density to match the view density before scaling, so that scaling
            // algorithm takes destination density into account.
            DisplayMetrics displayMetrics = new DisplayMetrics();
            displayMetrics.setToDefaults();
            bTemp.setDensity(displayMetrics.densityDpi);

            // Orient the image when orientation is set.
            if (autoRotate) {
                // Only set the orientation if it is uninitialized
                if (orientation < 0) {
                    orientation = getOrientation();
                }
                if (orientation > 0) {
                    return getRotatedBitmap(bTemp, orientation);
                }
            }

            if (bTemp.getNinePatchChunk() != null) {
                // Don't scale nine-patches
                b = bTemp;
                bTemp = null;
            } else {
                Log.d(TAG, "Scaling bitmap to " + destWidth + "x" + destHeight, Log.DEBUG_MODE);

                // If anyDensity=false, meaning Android is automatically scaling
                // pixel dimensions, need to do that here as well, because Bitmap width/height
                // calculations do _not_ do that automatically.
                if (anyDensityFalse && displayMetrics.density != 1f) {
                    destWidth = (int) (destWidth * displayMetrics.density + 0.5f); // 0.5 is to force round up of dimension. Casting to int drops decimals.
                    destHeight = (int) (destHeight * displayMetrics.density + 0.5f);
                }

                // Created a scaled copy of the bitmap. Note we will get
                // back the same bitmap if no scaling is required.
                b = Bitmap.createScaledBitmap(bTemp, destWidth, destHeight, true);
            }

        } catch (OutOfMemoryError e) {
            oomOccurred = true;
            Log.e(TAG, "Unable to load bitmap. Not enough memory: " + e.getMessage(), e);

        } finally {
            // Recycle the temporary bitmap only if it isn't
            // the same instance as our scaled bitmap.
            if (bTemp != null && bTemp != b) {
                bTemp.recycle();
                bTemp = null;
            }
        }

    } finally {
        try {
            is.close();
        } catch (IOException e) {
            Log.e(TAG, "Problem closing stream: " + e.getMessage(), e);
        }
    }
    if (Log.isDebugModeEnabled()) {
        StringBuilder sb = new StringBuilder();
        sb.append("Details of returned bitmap: .getWidth()=" + b.getWidth());
        sb.append("; getHeight()=" + b.getHeight());
        sb.append("; getDensity()=" + b.getDensity());
        Log.d(TAG, sb.toString());
    }
    return b;
}