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:by.zatta.pilight.connection.ConnectionService.java

private static Bitmap bigPic(int png) {
    Bitmap mBitmap = BitmapFactory.decodeResource(aCtx.getResources(), png);
    int height = (int) aCtx.getResources().getDimension(android.R.dimen.notification_large_icon_height);
    int width = (int) aCtx.getResources().getDimension(android.R.dimen.notification_large_icon_width);
    mBitmap = Bitmap.createScaledBitmap(mBitmap, width / 3, height / 3, false);
    return mBitmap;
}

From source file:com.dunrite.xpaper.utility.Utils.java

/**
 * TODO: DEPRECATE/*from w  w w. jav a  2 s . c o m*/
 * Combines two images into one while also coloring each separate image
 *
 * @param background the main background drawable
 * @param foreground the drawable in the front of the background]
 * @param context current context
 * @return colorized and combined drawable
 *
 * can add a 3rd parameter 'String loc' if you want to save the new image.
 * left some code to do that at the bottom
 */
public static Drawable combineImages(Drawable background, Drawable foreground, Drawable deviceMisc, int color1,
        int color2, String type, Context context) {
    Bitmap cs;
    Bitmap device = null;
    int width;
    int height;

    //convert from drawable to bitmap
    Bitmap back = ((BitmapDrawable) background).getBitmap();
    back = back.copy(Bitmap.Config.ARGB_8888, true);

    Bitmap x = ((BitmapDrawable) foreground).getBitmap();
    x = x.copy(Bitmap.Config.ARGB_8888, true);

    if (type.equals("device")) {
        device = ((BitmapDrawable) deviceMisc).getBitmap();
        device = device.copy(Bitmap.Config.ARGB_8888, true);
    }
    //initialize Canvas
    if (type.equals("preview") || type.equals("device")) {
        width = back.getWidth() / 2;
        height = back.getHeight() / 2;
    } else {
        width = back.getWidth();
        height = back.getHeight();
    }
    cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas comboImage = new Canvas(cs);

    //Filter for Background
    Paint paint1 = new Paint();
    paint1.setFilterBitmap(false);
    paint1.setColorFilter(new PorterDuffColorFilter(color1, PorterDuff.Mode.SRC_ATOP));

    //Filter for Foreground
    Paint paint2 = new Paint();
    paint2.setFilterBitmap(false);
    paint2.setColorFilter(new PorterDuffColorFilter(color2, PorterDuff.Mode.SRC_ATOP));

    //Draw both images
    if (type.equals("preview") || type.equals("device")) {
        if (type.equals("device"))
            comboImage.drawBitmap(
                    Bitmap.createScaledBitmap(device, device.getWidth() / 2, device.getHeight() / 2, true), 0,
                    0, null);
        comboImage.drawBitmap(Bitmap.createScaledBitmap(back, back.getWidth() / 2, back.getHeight() / 2, true),
                0, 0, paint1);
        comboImage.drawBitmap(Bitmap.createScaledBitmap(x, x.getWidth() / 2, x.getHeight() / 2, true), 0, 0,
                paint2);
    } else {
        comboImage.drawBitmap(back, 0, 0, paint1);
        comboImage.drawBitmap(x, 0, 0, paint2);
    }

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

From source file:net.ustyugov.jtalk.Notify.java

public static void messageNotify(String account, String fullJid, Type type, String text) {
    JTalkService service = JTalkService.getInstance();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(service);
    String currentJid = JTalkService.getInstance().getCurrentJid();
    String from = fullJid;/*from ww  w  . java 2s .  c om*/
    if (type == Type.Direct)
        from = StringUtils.parseBareAddress(fullJid);

    String ignored = prefs.getString("IgnoreJids", "");
    if (ignored.toLowerCase().contains(from.toLowerCase()))
        return;

    int color = Color.GREEN;
    try {
        color = Integer.parseInt(prefs.getString("lightsColor", Color.GREEN + ""));
    } catch (NumberFormatException nfe) {
    }

    String nick = from;
    if (service.getConferencesHash(account).containsKey(from)) {
        nick = StringUtils.parseName(from);
    } else if (service.getConferencesHash(account).containsKey(StringUtils.parseBareAddress(from))) {
        nick = StringUtils.parseResource(from);
    } else {
        Roster roster = JTalkService.getInstance().getRoster(account);
        if (roster != null) {
            RosterEntry re = roster.getEntry(from);
            if (re != null && re.getName() != null)
                nick = re.getName();
        }
    }

    String ticker = "";
    boolean include = prefs.getBoolean("MessageInNotification", false);
    if (include) {
        int count = Integer.parseInt(prefs.getString("MessageInNotificationCount", "64"));
        if (count > 0 && count < text.length())
            text = text.substring(0, count);
    }
    String vibration = prefs.getString("vibrationMode", "1");
    Vibrator vibrator = (Vibrator) service.getSystemService(Context.VIBRATOR_SERVICE);
    boolean vibro = false;
    boolean sound = true;
    String soundPath = "";

    if (type == Type.Conference) {
        if (!currentJid.equals(from) || currentJid.equals("me")) {
            if (!prefs.getBoolean("soundDisabled", false)) {
                if (vibration.equals("1") || vibration.equals("4"))
                    vibrator.vibrate(200);
                new SoundTask().execute("");
            }
        }
        return;
    } else if (type == Type.Direct) {
        text = StringUtils.parseResource(fullJid) + ": " + text;
        if (!prefs.getBoolean("soundDisabled", false)) {
            if (vibration.equals("1") || vibration.equals("3") || vibration.equals("4"))
                vibro = true;
            soundPath = prefs.getString("ringtone_direct", "");
        }
    } else {
        if (!prefs.getBoolean("soundDisabled", false)) {
            if (vibration.equals("1") || vibration.equals("2") || vibration.equals("3"))
                vibro = true;
            soundPath = prefs.getString("ringtone", "");
        }
    }

    if (soundPath.equals(""))
        sound = false;

    if (!currentJid.equals(from) || currentJid.equals("me")) {
        if (vibro)
            vibrator.vibrate(200);

        if (include) {
            ticker = service.getString(R.string.NewMessageFrom) + " " + nick + ": " + text;
        } else
            ticker = service.getString(R.string.NewMessageFrom) + " " + nick;

        Uri sound_file = Uri.parse(soundPath);

        String key = account + "/" + from;
        int id = 11 + ids.size();
        if (ids.containsKey(key))
            id = ids.get(key);
        else
            ids.put(key, id);

        Intent i = new Intent(service, Chat.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        i.setAction(ids + "");
        i.putExtra("jid", from);
        i.putExtra("account", account);
        PendingIntent contentIntent = PendingIntent.getActivity(service, 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Bitmap largeIcon = BitmapFactory.decodeResource(service.getResources(), R.drawable.stat_msg);
        if (type == Type.Direct)
            largeIcon = BitmapFactory.decodeResource(service.getResources(), R.drawable.icon_muc);
        else {
            if (prefs.getBoolean("LoadNotifyAvatar", true)) {
                String filePath = Constants.PATH + fullJid.replaceAll("/", "%");
                File a = new File(filePath);
                if (a.exists()) {
                    largeIcon = BitmapFactory.decodeFile(filePath);

                    int width = largeIcon.getWidth();
                    if (width > 96) {
                        double k = (double) width / (double) 96;
                        int h = (int) (largeIcon.getHeight() / k);
                        largeIcon = Bitmap.createScaledBitmap(largeIcon, 96, h, true);
                    }
                }
            }
        }

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(service);
        mBuilder.setLargeIcon(largeIcon);
        mBuilder.setSmallIcon(R.drawable.stat_msg);
        mBuilder.setLights(color, 2000, 3000);
        mBuilder.setContentTitle(nick);
        mBuilder.setContentText(text);
        mBuilder.setContentIntent(contentIntent);
        mBuilder.setTicker(ticker);
        mBuilder.setNumber(service.getMessagesCount(account, from));
        mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        if (sound)
            mBuilder.setSound(sound_file);

        NotificationCompat.BigTextStyle bts = new NotificationCompat.BigTextStyle();
        bts.setBigContentTitle(nick);
        bts.bigText(text);
        mBuilder.setStyle(bts);

        NotificationManager mng = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
        mng.notify(id, mBuilder.build());
    }
}

From source file:FacebookImageLoader.java

public static Bitmap processImageFromBitmap(final Bitmap bitmap, final int maxDimension) {
    // Check input
    if (bitmap == null) {
        return null;
    }/*  ww w. j  a  v  a2s . c o  m*/

    // Calculate the resize ratio. Make the longest side
    // somewhere in the vicinity of 'maxDimension' pixels.
    int maxSide = Math.max(bitmap.getWidth(), bitmap.getHeight());
    float newWidth = bitmap.getWidth();
    float newHeight = bitmap.getHeight();
    float ratio = 0;

    if (maxSide > maxDimension) {
        ratio = (float) maxDimension / (float) maxSide;
        newWidth *= ratio;
        newHeight *= ratio;
    }

    try {
        return Bitmap.createScaledBitmap(bitmap, Math.round(newWidth), Math.round(newHeight), false);
    } catch (OutOfMemoryError e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.orpheusdroid.screenrecorder.RecorderService.java

private NotificationCompat.Builder createNotification(NotificationCompat.Action action) {
    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

    Intent recordStopIntent = new Intent(this, RecorderService.class);
    recordStopIntent.setAction(Const.SCREEN_RECORDING_STOP);
    PendingIntent precordStopIntent = PendingIntent.getService(this, 0, recordStopIntent, 0);

    Intent UIIntent = new Intent(this, MainActivity.class);
    PendingIntent notificationContentIntent = PendingIntent.getActivity(this, 0, UIIntent, 0);

    NotificationCompat.Builder notification = new NotificationCompat.Builder(this)
            .setContentTitle(getResources().getString(R.string.screen_recording_notification_title))
            .setTicker(getResources().getString(R.string.screen_recording_notification_title))
            .setSmallIcon(R.drawable.ic_notification)
            .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false)).setUsesChronometer(true)
            .setOngoing(true).setContentIntent(notificationContentIntent).setPriority(Notification.PRIORITY_MAX)
            .addAction(R.drawable.ic_notification_stop,
                    getResources().getString(R.string.screen_recording_notification_action_stop),
                    precordStopIntent);/*ww  w .  j  a va  2s  .c  o  m*/
    if (action != null)
        notification.addAction(action);
    return notification;
}

From source file:com.example.android.wardrobe.HomeActivity.java

private Bitmap getResizedImageBitmap(Uri uri, int widthLimit, int heightLimit) {
    InputStream input = null;/*from  ww  w  . java2  s .  com*/
    int mWidth = 0, mHeight = 0;
    try {
        input = this.getContentResolver().openInputStream(uri);
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(input, null, opt);
        mWidth = opt.outWidth;
        mHeight = opt.outHeight;
    } catch (FileNotFoundException e) {
        // Ignore
    } finally {
        if (null != input) {
            try {
                input.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }

    int outWidth = mWidth;
    int outHeight = mHeight;

    int scaleFactor = 1;
    /*    int checkWidth = widthLimit;
        int checkHeight = heightLimit;
        if(checkWidth == -1){*/
    int min = Math.min(outWidth, outHeight);
    if (widthLimit == -1 || heightLimit == -1) {
        //int max = 260000;
        int max = 1000000;
        int w = outWidth;
        int h = outHeight;
        for (int i = w; i >= 1; i--) {
            int nh = Math.round(((float) h * (float) i) / (float) w);
            if (nh * i <= max) {
                widthLimit = i;
                heightLimit = nh;
                break;
            }
        }
    }
    //      checkWidth = 500; checkHeight = 500;
    //  }
    while ((outWidth / scaleFactor / 2 >= widthLimit && outHeight / scaleFactor / 2 >= heightLimit)) {
        scaleFactor *= 2;
    }
    /*    while ((min / scaleFactor > max1)) {
      scaleFactor *= 2;
    }*/
    // scaleFactor /= 2;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = false;
    options.inDither = false;
    options.inSampleSize = scaleFactor;
    options.inScaled = false;
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    try {
        input = this.getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    //    int quality = MessageUtils.IMAGE_COMPRESSION_QUALITY;
    Bitmap b = BitmapFactory.decodeStream(input, null, options);
    if (b == null) {
        return null;
    }
    Bitmap bi = Bitmap.createScaledBitmap(b, widthLimit, heightLimit, true);
    return bi;
}

From source file:github.daneren2005.dsub.util.FileUtil.java

public static Bitmap getScaledBitmap(Bitmap bitmap, int size, boolean allowUnscaled) {
    // Don't waste time scaling if the difference is minor
    // Large album arts still need to be scaled since displayed as is on now playing!
    if (allowUnscaled && size < 400 && bitmap.getWidth() < (size * 1.1)) {
        return bitmap;
    } else {/*from w  w w .j av a  2  s .  c  o  m*/
        return Bitmap.createScaledBitmap(bitmap, size, Util.getScaledHeight(bitmap, size), true);
    }
}

From source file:com.gmail.jiangyang5157.cardboard.net.DescriptionRequest.java

/**
 * The real guts of parseNetworkResponse. Broken out for readability.
 *///  w  ww  . jav  a  2s  .c  om
private Response<Object> doBitmapParse(NetworkResponse response) {
    byte[] data = response.data;
    BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
    Bitmap bitmap;
    if (mMaxWidth == 0 && mMaxHeight == 0) {
        decodeOptions.inPreferredConfig = mDecodeConfig;
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
    } else {
        // If we have to resize this image, first get the natural bounds.
        decodeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);
        int actualWidth = decodeOptions.outWidth;
        int actualHeight = decodeOptions.outHeight;

        // Then compute the dimensions we would ideally like to decode to.
        int desiredWidth = getResizedDimension(mMaxWidth, mMaxHeight, actualWidth, actualHeight, mScaleType);
        int desiredHeight = getResizedDimension(mMaxHeight, mMaxWidth, actualHeight, actualWidth, mScaleType);

        // Decode to the nearest power of two scaling factor.
        decodeOptions.inJustDecodeBounds = false;
        decodeOptions.inSampleSize = findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
        Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, decodeOptions);

        // If necessary, scale down to the maximal acceptable size.
        if (tempBitmap != null
                && (tempBitmap.getWidth() > desiredWidth || tempBitmap.getHeight() > desiredHeight)) {
            bitmap = Bitmap.createScaledBitmap(tempBitmap, desiredWidth, desiredHeight, true);
            tempBitmap.recycle();
        } else {
            bitmap = tempBitmap;
        }
    }

    if (bitmap == null) {
        return Response.error(new ParseError(response));
    } else {
        return Response.success(bitmap, HttpHeaderParser.parseCacheHeaders(response));
    }
}

From source file:com.semfapp.adamdilger.semf.Take5PdfDocument.java

private static Bitmap resize(Bitmap image, int maxWidth, int maxHeight) {

    int width = image.getWidth();
    int height = image.getHeight();
    float ratioBitmap = (float) width / (float) height;
    float ratioMax = (float) maxWidth / (float) maxHeight;

    Log.d(TAG, "resize: " + String.format("width: %d, height: %d, ratioBitmap: %f, ratioMax: %f", width, height,
            ratioBitmap, ratioMax));//from  w w w .  j  av  a2s  . c om

    int finalWidth = maxWidth;
    int finalHeight = maxHeight;
    if (ratioMax > 1) {
        finalWidth = (int) ((float) maxHeight * ratioBitmap);
    } else {
        finalHeight = (int) ((float) maxWidth / ratioBitmap);
    }

    if (finalHeight > maxHeight) {
        finalWidth = (int) ((float) maxHeight * ratioBitmap);
        finalHeight = maxHeight;
    }

    image = Bitmap.createScaledBitmap(image, finalWidth, finalHeight, true);
    return image;
}

From source file:github.madmarty.madsonic.util.ImageLoader.java

private Bitmap createReflection(Bitmap originalImage) {

    //   int reflectionH = 80;

    int width = originalImage.getWidth();
    int height = originalImage.getHeight();

    // Height of reflection
    int reflectionHeight = height / 2;

    // The gap we want between the reflection and the original image
    final int reflectionGap = 4;

    // Create a new bitmap with same width but taller to fit reflection
    Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + reflectionHeight),
            Bitmap.Config.ARGB_8888);//from   w  w  w  .j  ava 2  s  . c o m

    //// ----

    Bitmap reflection = Bitmap.createBitmap(width, reflectionHeight, Bitmap.Config.ARGB_8888);
    Bitmap blurryBitmap = Bitmap.createBitmap(originalImage, 0, height - reflectionHeight, height,
            reflectionHeight);

    // cheap and easy scaling algorithm; down-scale it, then
    // upscale it. The filtering during the scale operations
    // will blur the resulting image
    blurryBitmap = Bitmap
            .createScaledBitmap(
                    Bitmap.createScaledBitmap(blurryBitmap, blurryBitmap.getWidth() / 2,
                            blurryBitmap.getHeight() / 2, true),
                    blurryBitmap.getWidth(), blurryBitmap.getHeight(), true);

    // This shadier will hold a cropped, inverted,
    // blurry version of the original image
    BitmapShader bitmapShader = new BitmapShader(blurryBitmap, TileMode.CLAMP, TileMode.CLAMP);
    Matrix invertMatrix = new Matrix();
    invertMatrix.setScale(1f, -1f);
    invertMatrix.preTranslate(0, -reflectionHeight);
    bitmapShader.setLocalMatrix(invertMatrix);

    // This shader holds an alpha gradient
    Shader alphaGradient = new LinearGradient(0, 0, 0, reflectionHeight, 0x80ffffff, 0x00000000,
            TileMode.CLAMP);

    // This shader combines the previous two, resulting in a
    // blurred, fading reflection
    ComposeShader compositor = new ComposeShader(bitmapShader, alphaGradient, PorterDuff.Mode.DST_IN);

    Paint reflectionPaint = new Paint();
    reflectionPaint.setShader(compositor);

    // Draw the reflection into the bitmap that we will return
    Canvas canvas = new Canvas(reflection);
    canvas.drawRect(0, 0, reflection.getWidth(), reflection.getHeight(), reflectionPaint);

    /// -----

    // Create a new Canvas with the bitmap that's big enough for
    // the image plus gap plus reflection
    Canvas finalcanvas = new Canvas(bitmapWithReflection);

    // Draw in the original image
    finalcanvas.drawBitmap(originalImage, 0, 0, null);

    // Draw in the gap
    Paint defaultPaint = new Paint();

    // transparent gap
    defaultPaint.setColor(0);

    finalcanvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);

    // Draw in the reflection
    finalcanvas.drawBitmap(reflection, 0, height + reflectionGap, null);

    return bitmapWithReflection;
}