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:com.actionbarsherlock.sample.hcgallery.MainActivity.java

void showNotification(boolean custom) {
    final Resources res = getResources();
    final NotificationManager notificationManager = (NotificationManager) getSystemService(
            NOTIFICATION_SERVICE);/*from   w ww .ja  v  a  2s.  c om*/

    Notification.Builder builder = new Notification.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_notify_example).setAutoCancel(true)
            .setTicker(getString(R.string.notification_text))
            .setContentIntent(getDialogPendingIntent("Tapped the notification entry."));

    if (custom) {
        // Sets a custom content view for the notification, including an image button.
        RemoteViews layout = new RemoteViews(getPackageName(), R.layout.notification);
        layout.setTextViewText(R.id.notification_title, getString(R.string.app_name));
        layout.setOnClickPendingIntent(R.id.notification_button,
                getDialogPendingIntent("Tapped the 'dialog' button in the notification."));
        builder.setContent(layout);

        // Notifications in Android 3.0 now have a standard mechanism for displaying large
        // bitmaps such as contact avatars. Here, we load an example image and resize it to the
        // appropriate size for large bitmaps in notifications.
        Bitmap largeIconTemp = BitmapFactory.decodeResource(res, R.drawable.notification_default_largeicon);
        Bitmap largeIcon = Bitmap.createScaledBitmap(largeIconTemp,
                res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
                res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height), false);
        largeIconTemp.recycle();

        builder.setLargeIcon(largeIcon);

    } else {
        builder.setNumber(7) // An example number.
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.notification_text));
    }

    notificationManager.notify(NOTIFICATION_DEFAULT, builder.getNotification());
}

From source file:com.eyekabob.ArtistInfo.java

private void handleImageResponse(Bitmap img) {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    float metWidth = metrics.widthPixels;
    float imgWidth = img.getWidth();
    float ratio = metWidth / imgWidth;
    // Add a little buffer room
    int newWidth = (int) Math.floor(img.getWidth() * ratio) - 50;
    int newHeight = (int) Math.floor(img.getHeight() * ratio) - 50;

    ImageView iv = (ImageView) findViewById(R.id.infoImageView);
    Bitmap rescaledImg = Bitmap.createScaledBitmap(img, newWidth, newHeight, false);
    iv.setImageBitmap(rescaledImg);//from w  ww  .  j a  v  a  2  s . co  m
    imageInfoReturned = true;
    dismissDialogIfReady();
}

From source file:com.albedinsky.android.support.intent.ImageIntent.java

/**
 * Processes the given result <var>data</var> intent to obtain a user's picked image.
 * <p>/*from  ww w .j a  v a  2s.c  o m*/
 * <b>Note</b>, that in case of {@link #REQUEST_CODE_CAMERA}, the captured photo's bitmap will be
 * received only in quality of "place holder" image, not as full quality image. For full quality
 * photo pass an instance of Uri to {@link #output(Uri)} and the bitmap of the captured
 * photo will be stored on the specified uri.
 *
 * @param requestCode The request code from {@link Activity#onActivityResult(int, int, Intent)} or
 *                    {@link android.support.v4.app.Fragment#onActivityResult(int, int, Intent)}.
 *                    Can be only one of {@link #REQUEST_CODE_CAMERA} or {@link #REQUEST_CODE_GALLERY}.
 * @param resultCode  The result code from {@link Activity#onActivityResult(int, int, Intent)} or
 *                    {@link android.support.v4.app.Fragment#onActivityResult(int, int, Intent)}.
 *                    If {@link Activity#RESULT_OK}, the passed <var>data</var> will be processed,
 *                    otherwise {@code null} will be returned.
 * @param data        The data from {@link Activity#onActivityResult(int, int, Intent)} or
 *                    {@link android.support.v4.app.Fragment#onActivityResult(int, int, Intent)}.
 * @param context     Current valid context.
 * @param options     Image options to adjust obtained bitmap.
 * @return Instance of Bitmap obtained from the given <var>data</var> Intent.
 */
@Nullable
@SuppressWarnings("deprecation")
public static Bitmap processResultIntent(int requestCode, int resultCode, @Nullable Intent data,
        @NonNull Context context, @Nullable ImageOptions options) {
    if (data == null || resultCode != Activity.RESULT_OK) {
        // User canceled the intent or no data are available.
        return null;
    }
    switch (requestCode) {
    case REQUEST_CODE_GALLERY:
        final Uri imageUri = data.getData();
        Bitmap galleryImage = null;

        if (imageUri != null) {
            InputStream stream = null;
            try {
                stream = context.getContentResolver().openInputStream(imageUri);
            } catch (Exception e) {
                Log.e(TAG, "Unable to open image content at uri(" + imageUri + ").", e);
            } finally {
                if (stream != null) {
                    if (options != null) {
                        // Get the dimensions of the returned bitmap.
                        final BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                        bmOptions.inJustDecodeBounds = true;
                        BitmapFactory.decodeStream(stream, null, bmOptions);
                        final int bmWidth = bmOptions.outWidth;
                        final int bmHeight = bmOptions.outHeight;

                        // Compute how much to scale the bitmap.
                        final int scaleFactor = Math.min(bmWidth / options.width, bmHeight / options.height);

                        // Decode scaled bitmap.
                        bmOptions.inJustDecodeBounds = false;
                        bmOptions.inSampleSize = scaleFactor;
                        bmOptions.inPurgeable = true;
                        galleryImage = BitmapFactory.decodeStream(stream, null, bmOptions);
                    } else {
                        galleryImage = BitmapFactory.decodeStream(stream);
                    }

                    try {
                        stream.close();
                    } catch (IOException e) {
                        Log.e(TAG, "Unable to close image content at uri(" + imageUri + ").", e);
                    }
                }
            }
        }
        return galleryImage;
    case REQUEST_CODE_CAMERA:
        final Bundle extras = data.getExtras();
        try {
            final Bitmap cameraImage = (extras != null) ? (Bitmap) extras.get("data") : null;
            if (cameraImage != null && options != null) {
                return Bitmap.createScaledBitmap(cameraImage, options.width, options.height, false);
            }
            return cameraImage;
        } catch (Exception e) {
            Log.e(TAG, "Failed to retrieve captured image.", e);
        }
    }
    return null;
}

From source file:www.image.ImageManager.java

/**
 * ???Bitmap/*from   ww w.  j a va2  s . com*/
 * @param bitmap
 * @param maxWidth
 * @param maxHeight
 * @param quality 1~100
 * @return
 */
public Bitmap resizeBitmap(Bitmap bitmap, int maxWidth, int maxHeight) {

    int originWidth = bitmap.getWidth();
    int originHeight = bitmap.getHeight();

    // no need to resize
    if (originWidth < maxWidth && originHeight < maxHeight)
        return bitmap;

    int width = originWidth;
    int height = originHeight;

    // , ??
    if (originWidth > maxWidth) {
        width = maxWidth;

        double i = originWidth * 1.0 / maxWidth;
        height = (int) Math.floor(originHeight / i);

        bitmap = Bitmap.createScaledBitmap(bitmap, width, height, false);
    }

    // , ?
    if (height > maxHeight) {
        height = maxHeight;
        bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
    }
    return bitmap;
}

From source file:com.bamobile.fdtks.util.Tools.java

public static Bitmap getBitmapFromURL(Context context, String imageUrl, int width, int height) {
    if (imageUrl != null && imageUrl.length() > 0) {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(imageUrl.replace(" ", "%20"));
        try {//from   w ww.  j  a va2  s  .  c  om
            HttpResponse response = client.execute(get);
            byte[] content = EntityUtils.toByteArray(response.getEntity());
            //get the dimensions of the image
            BitmapFactory.Options opts = new BitmapFactory.Options();
            opts.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(content, 0, content.length, opts);

            // get the image and scale it appropriately
            opts.inJustDecodeBounds = false;
            opts.inSampleSize = Math.max(opts.outWidth / width, opts.outHeight / height);

            Bitmap bitmap = BitmapFactory.decodeByteArray(content, 0, content.length, opts);
            if (bitmap == null) {
                return null;
            }

            int scaledWidth = bitmap.getWidth();
            int scaledHeight = bitmap.getHeight();

            if (scaledWidth < scaledHeight) {
                float scale = width / (float) scaledWidth;

                scaledWidth = width;
                scaledHeight = (int) Math.ceil(scaledHeight * scale);
                if (scaledHeight < height) {
                    scale = height / (float) scaledHeight;

                    scaledHeight = height;
                    scaledWidth = (int) Math.ceil(scaledWidth * scale);
                }
            } else {
                float scale = height / (float) scaledHeight;

                scaledHeight = height;
                scaledWidth = (int) Math.ceil(scaledWidth * scale);

                if (scaledWidth < width) {
                    scale = width / (float) scaledWidth;

                    scaledWidth = width;
                    scaledHeight = (int) Math.ceil(scaledHeight * scale);
                }
            }

            Bitmap bmp = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, false);

            bitmap.recycle();
            bitmap = null;

            return bmp;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    return null;
}

From source file:no.ntnu.idi.socialhitchhiking.myAccount.MyAccountCar.java

/**
* Gets and resizes a {@link Bitmap} from a {@link Uri} using width and height.
* @param uri//from   w w w .  j  a  v  a2s .co m
* @param width
* @param height
* @return
*/
private Bitmap getBitmap(Uri uri, int width, int height) {
    InputStream in = null;
    try {
        int IMAGE_MAX_SIZE = Math.max(width, height);
        in = getContentResolver().openInputStream(uri);

        //Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;

        BitmapFactory.decodeStream(in, null, o);
        in.close();

        int scale = 1;
        if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
            scale = (int) Math.pow(2, (int) Math.round(
                    Math.log(IMAGE_MAX_SIZE / (double) Math.max(o.outHeight, o.outWidth)) / Math.log(0.5)));
        }

        //adjust sample size such that the image is bigger than the result
        scale -= 1;

        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        in = getContentResolver().openInputStream(uri);
        Bitmap b = BitmapFactory.decodeStream(in, null, o2);
        in.close();

        //scale bitmap to desired size
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, width, height, false);

        //free memory
        b.recycle();

        return scaledBitmap;

    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }
    return null;
}

From source file:com.grarak.kerneladiutor.utils.ViewUtils.java

private static Bitmap resizeBitmap(Bitmap bitmap, int newWidth, int newHeight) {
    return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
}

From source file:com.wit.android.support.content.intent.ImageIntent.java

/**
 * Processes the given result <var>data</var> to obtain the requested Bitmap.
 * <p>//  ww w.  j a  va 2  s. c  o m
 * <b>Note</b>, that in case of {@link #REQUEST_CODE_CAMERA}, the obtained Bitmap will be only todo....
 * For full quality image pass an instance of Uri to {@link #output(android.net.Uri)}.
 *
 * @param requestCode The request code from {@link Activity#onActivityResult(int, int, android.content.Intent)} or
 *                    {@link android.support.v4.app.Fragment#onActivityResult(int, int, android.content.Intent)}.
 *                    Can be only one of {@link #REQUEST_CODE_CAMERA} or {@link #REQUEST_CODE_GALLERY}.
 * @param resultCode  The result code from {@link Activity#onActivityResult(int, int, android.content.Intent)} or
 *                    {@link android.support.v4.app.Fragment#onActivityResult(int, int, android.content.Intent)}.
 *                    If {@link Activity#RESULT_OK}, the passed <var>data</var> will be processed,
 *                    otherwise {@code null} will be returned.
 * @param data        The data from {@link Activity#onActivityResult(int, int, android.content.Intent)} or
 *                    {@link android.support.v4.app.Fragment#onActivityResult(int, int, android.content.Intent)}.
 * @param context     Current valid context.
 * @param options     Image options to adjust obtained bitmap.
 * @return Instance of Bitmap obtained from the given <var>data</var> Intent.
 */
@Nullable
public static Bitmap processResultIntent(int requestCode, int resultCode, @Nullable Intent data,
        @NonNull Context context, @Nullable ImageOptions options) {
    if (data != null) {
        switch (resultCode) {
        case Activity.RESULT_OK:
            switch (requestCode) {
            case REQUEST_CODE_GALLERY:
                final Uri imageUri = data.getData();
                Bitmap galleryImage = null;

                if (imageUri != null) {
                    InputStream stream = null;
                    try {
                        stream = context.getContentResolver().openInputStream(imageUri);
                    } catch (Exception e) {
                        Log.e(TAG, "Unable to open image content: " + imageUri, e);
                    } finally {
                        if (stream != null) {
                            if (options != null) {
                                // Get the dimensions of the returned bitmap.
                                final BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                                bmOptions.inJustDecodeBounds = true;
                                BitmapFactory.decodeStream(stream, null, bmOptions);
                                final int bmWidth = bmOptions.outWidth;
                                final int bmHeight = bmOptions.outHeight;

                                // Compute how much to scale the bitmap.
                                final int scaleFactor = Math.min(bmWidth / options.width,
                                        bmHeight / options.height);

                                // Decode scaled bitmap.
                                bmOptions.inJustDecodeBounds = false;
                                bmOptions.inSampleSize = scaleFactor;
                                bmOptions.inPurgeable = true;
                                galleryImage = BitmapFactory.decodeStream(stream, null, bmOptions);
                            } else {
                                galleryImage = BitmapFactory.decodeStream(stream);
                            }

                            try {
                                stream.close();
                            } catch (IOException e) {
                                Log.e(TAG, "Unable to close image content: " + imageUri, e);
                            }
                        }
                    }
                }
                return galleryImage;
            case REQUEST_CODE_CAMERA:
                final Bundle extras = data.getExtras();
                try {
                    final Bitmap cameraImage = (extras != null) ? (Bitmap) extras.get("data") : null;
                    if (cameraImage != null && options != null) {
                        return Bitmap.createScaledBitmap(cameraImage, options.width, options.height, false);
                    }
                    return cameraImage;
                } catch (Exception e) {
                    Log.e(TAG, "Failed to retrieve captured image.", e);
                }
            }
            break;
        case Activity.RESULT_CANCELED:
            // User canceled get image action.
            break;
        }
    }
    return null;
}

From source file:org.amahi.anywhere.util.MediaNotificationManager.java

private Bitmap getAudioPlayerNotificationArtwork(Bitmap audioAlbumArt) {
    int iconHeight = (int) mService.getResources().getDimension(android.R.dimen.notification_large_icon_height);
    int iconWidth = (int) mService.getResources().getDimension(android.R.dimen.notification_large_icon_width);

    if (audioAlbumArt == null) {
        return null;
    }/*from w w w.  ja  v a  2s  .  co  m*/

    return Bitmap.createScaledBitmap(audioAlbumArt, iconWidth, iconHeight, false);
}

From source file:de.enlightened.peris.ProfileFragment.java

@Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        if (requestCode == CAMERA_PIC_REQUEST) {
            try {
                final File imagesFolder = new File(Environment.getExternalStorageDirectory(), "temp");
                imagesFolder.mkdirs();//from w ww. j  a v  a  2 s.c o m
                final File image = new File(imagesFolder, "temp.jpg");

                this.uploadPicPath = image.getPath();
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                final int imageWidth = options.outWidth;
                options = new BitmapFactory.Options();

                if (imageWidth > (DESIRED_PIC_SIZE * 8)) {
                    options.inSampleSize = 8;
                } else if (imageWidth > (DESIRED_PIC_SIZE * 4)) {
                    options.inSampleSize = 4;
                } else if (imageWidth > (DESIRED_PIC_SIZE * 2)) {
                    options.inSampleSize = 2;
                } else {
                    options.inSampleSize = 1;
                }

                Bitmap thumbnail2 = BitmapFactory.decodeFile(this.uploadPicPath, options);
                thumbnail2 = Bitmap.createScaledBitmap(thumbnail2, THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
                this.uploadPic = thumbnail2;

                Log.d(TAG, "Avatar Size: " + this.uploadPic.getWidth() + "x" + this.uploadPic.getHeight());

                this.submitpic();
            } catch (Exception e) {
                final Toast toast = Toast.makeText(this.activity, "Error loading image!" + e.getMessage(),
                        Toast.LENGTH_LONG);
                toast.show();
                return;
            }
        } else {
            if (requestCode == GALLERY_PIC_REQUEST) {
                try {
                    final Uri currImageURI;
                    currImageURI = data.getData();
                    final String[] proj = { MediaStore.Images.Media.DATA };
                    final Cursor cursor = this.activity.managedQuery(currImageURI, proj, // Which columns to return
                            null, // WHERE clause; which rows to return (all rows)
                            null, // WHERE clause selection arguments (none)
                            null); // Order-by clause (ascending by name)
                    final int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();

                    this.uploadPicPath = cursor.getString(columnIndex);

                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    final int imageWidth = options.outWidth;
                    options = new BitmapFactory.Options();

                    if (imageWidth > DESIRED_PIC_SIZE * 8) {
                        options.inSampleSize = 8;
                    } else if (imageWidth > DESIRED_PIC_SIZE * 4) {
                        options.inSampleSize = 4;
                    } else if (imageWidth > DESIRED_PIC_SIZE * 2) {
                        options.inSampleSize = 2;
                    } else {
                        options.inSampleSize = 1;
                    }
                    Bitmap thumbnail2 = BitmapFactory.decodeFile(this.uploadPicPath, options);
                    thumbnail2 = Bitmap.createScaledBitmap(thumbnail2, THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
                    this.uploadPic = thumbnail2;

                    Log.d(TAG, "Avatar Size: " + this.uploadPic.getWidth() + "x" + this.uploadPic.getHeight());

                    this.submitpic();
                } catch (Exception e) {
                    final Toast toast = Toast.makeText(this.activity, "Can only upload locally stored content!",
                            Toast.LENGTH_LONG);
                    toast.show();
                    return;
                }
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}