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:de.ub0r.android.smsdroid.SmsReceiver.java

/**
 * Update new message {@link Notification}.
 *
 * @param context {@link Context}/*from  w w w. j  av a  2  s  .c  o  m*/
 * @param text    text of the last assumed unread message
 * @return number of unread messages
 */
static int updateNewMessageNotification(final Context context, final String text) {
    Log.d(TAG, "updNewMsgNoti(", context, ",", text, ")");
    final NotificationManager mNotificationMgr = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    final boolean enableNotifications = prefs.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_ENABLE, true);
    final boolean privateNotification = prefs.getBoolean(PreferencesActivity.PREFS_NOTIFICATION_PRIVACY, false);
    final boolean showPhoto = !privateNotification
            && prefs.getBoolean(PreferencesActivity.PREFS_CONTACT_PHOTO, true);
    if (!enableNotifications) {
        mNotificationMgr.cancelAll();
        Log.d(TAG, "no notification needed!");
    }
    final int[] status = getUnread(context.getContentResolver(), text);
    final int l = status[ID_COUNT];
    final int tid = status[ID_TID];

    // FIXME l is always -1..
    Log.d(TAG, "l: ", l);
    if (l < 0) {
        return l;
    }

    if (enableNotifications && (text != null || l == 0)) {
        mNotificationMgr.cancel(NOTIFICATION_ID_NEW);
    }
    Uri uri;
    PendingIntent pIntent;
    if (l == 0) {
        final Intent i = new Intent(context, ConversationListActivity.class);
        // add pending intent
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
    } else {
        final NotificationCompat.Builder nb = new NotificationCompat.Builder(context);
        boolean showNotification = true;
        Intent i;
        if (tid >= 0) {
            uri = Uri.parse(MessageListActivity.URI + tid);
            i = new Intent(Intent.ACTION_VIEW, uri, context, MessageListActivity.class);
            pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

            if (enableNotifications) {
                final Conversation conv = Conversation.getConversation(context, tid, true);
                if (conv != null) {
                    String a;
                    if (privateNotification) {
                        if (l == 1) {
                            a = context.getString(R.string.new_message_);
                        } else {
                            a = context.getString(R.string.new_messages_);
                        }
                    } else {
                        a = conv.getContact().getDisplayName();
                    }
                    showNotification = true;
                    nb.setSmallIcon(PreferencesActivity.getNotificationIcon(context));
                    nb.setTicker(a);
                    nb.setWhen(lastUnreadDate);
                    if (l == 1) {
                        String body;
                        if (privateNotification) {
                            body = context.getString(R.string.new_message);
                        } else {
                            body = lastUnreadBody;
                        }
                        if (body == null) {
                            body = context.getString(R.string.mms_conversation);
                        }
                        nb.setContentTitle(a);
                        nb.setContentText(body);
                        nb.setContentIntent(pIntent);
                        // add long text
                        nb.setStyle(new NotificationCompat.BigTextStyle().bigText(body));

                        // add actions
                        Intent nextIntent = new Intent(NotificationBroadcastReceiver.ACTION_MARK_READ);
                        nextIntent.putExtra(NotificationBroadcastReceiver.EXTRA_MURI, uri.toString());
                        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context, 0, nextIntent,
                                PendingIntent.FLAG_UPDATE_CURRENT);

                        nb.addAction(R.drawable.ic_menu_mark, context.getString(R.string.mark_read_),
                                nextPendingIntent);
                        nb.addAction(R.drawable.ic_menu_compose, context.getString(R.string.reply), pIntent);
                    } else {
                        nb.setContentTitle(a);
                        nb.setContentText(context.getString(R.string.new_messages, l));
                        nb.setContentIntent(pIntent);
                    }
                    if (showPhoto // just for the speeeeed
                            && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        try {
                            conv.getContact().update(context, false, true);
                        } catch (NullPointerException e) {
                            Log.e(TAG, "updating contact failed", e);
                        }
                        Drawable d = conv.getContact().getAvatar(context, null);
                        if (d instanceof BitmapDrawable) {
                            Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
                            // 24x24 dp according to android iconography  ->
                            // http://developer.android.com/design/style/iconography.html#notification
                            int px = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 64,
                                    context.getResources().getDisplayMetrics()));
                            nb.setLargeIcon(Bitmap.createScaledBitmap(bitmap, px, px, false));
                        }
                    }
                }
            }
        } else {
            uri = Uri.parse(MessageListActivity.URI);
            i = new Intent(Intent.ACTION_VIEW, uri, context, ConversationListActivity.class);
            pIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

            if (enableNotifications) {
                showNotification = true;
                nb.setSmallIcon(PreferencesActivity.getNotificationIcon(context));
                nb.setTicker(context.getString(R.string.new_messages_));
                nb.setWhen(lastUnreadDate);
                nb.setContentTitle(context.getString(R.string.new_messages_));
                nb.setContentText(context.getString(R.string.new_messages, l));
                nb.setContentIntent(pIntent);
                nb.setNumber(l);
            }
        }
        // add pending intent
        i.setFlags(i.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);

        if (enableNotifications && showNotification) {
            int[] ledFlash = PreferencesActivity.getLEDflash(context);
            nb.setLights(PreferencesActivity.getLEDcolor(context), ledFlash[0], ledFlash[1]);
            final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
            if (text != null) {
                final boolean vibrate = p.getBoolean(PreferencesActivity.PREFS_VIBRATE, false);
                final String s = p.getString(PreferencesActivity.PREFS_SOUND, null);
                Uri sound;
                if (s == null || s.length() <= 0) {
                    sound = null;
                } else {
                    sound = Uri.parse(s);
                }
                if (vibrate) {
                    final long[] pattern = PreferencesActivity.getVibratorPattern(context);
                    if (pattern.length == 1 && pattern[0] == 0) {
                        nb.setDefaults(Notification.DEFAULT_VIBRATE);
                    } else {
                        nb.setVibrate(pattern);
                    }
                }
                nb.setSound(sound);
            }
        }
        Log.d(TAG, "uri: ", uri);
        mNotificationMgr.cancel(NOTIFICATION_ID_NEW);
        if (enableNotifications && showNotification) {
            try {
                mNotificationMgr.notify(NOTIFICATION_ID_NEW, nb.getNotification());
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "illegal notification: ", nb, e);
            }
        }
    }
    Log.d(TAG, "return ", l, " (2)");
    //noinspection ConstantConditions
    AppWidgetManager.getInstance(context).updateAppWidget(new ComponentName(context, WidgetProvider.class),
            WidgetProvider.getRemoteViews(context, l, pIntent));
    return l;
}

From source file:nu.yona.app.ui.YonaActivity.java

private File compressFile(CropImage.ActivityResult result) {
    File file = new File(getFilesDir(), "prof_pic_" + System.currentTimeMillis() + ".jpeg|");
    try {//from  ww w.  j  av a2 s .  c  o m
        FileInputStream fis = new FileInputStream(result.getUri().getPath());
        Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
        imageBitmap = Bitmap.createScaledBitmap(imageBitmap, 90, 90, false);
        FileOutputStream fos = new FileOutputStream(file);
        imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    } catch (FileNotFoundException ex) {
        AppUtils.reportException(YonaActivity.class.getSimpleName(), ex, Thread.currentThread());
        return null;
    }
    return file;
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageAdapter.java

public void downloadFile(String subject3, int flag) {
    String imageName, imageDirNumber;

    imageDirNumber = getNumber(subject3);
    imageName = getTimestamp(subject3);/*w w w . jav  a 2 s  . c  om*/
    if (checkFile(imageDirNumber, imageName) == true) {
        if (flag == RECIEVED_IMAGE) {
            String p = fileDir + imageDirNumber + "/Recieved/" + imageName;
            Log.d("pp", p);
            try {
                Bitmap b = BitmapFactory.decodeFile(p);
                int[] size = messageActivity.getBitmapSize(b);
                b = Bitmap.createScaledBitmap(b, size[0], size[1], false);
                iv_recievedfile.setImageBitmap(b);
                // iv_recievedfile.setImageURI(Uri.parse(p));
            } catch (Exception e) {
                // TODO: handle exception
                iv_recievedfile.setImageResource(R.drawable.download_icon);
                setProgressBar(subject3);
            }
        } else if (flag == RECIEVED_VIDEO) {
            try {
                Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.google_video_icon);
                iv_recievedfile.setImageBitmap(b);
            } catch (Exception e) {
                // TODO: handle exception
                iv_recievedfile.setImageResource(R.drawable.download_icon);
                setProgressBar(subject3);
            }
        } else if (flag == RECIEVED_AUDIO) {
            try {
                Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.google_audio_icon);
                iv_recievedfile.setImageBitmap(b);
            } catch (Exception e) {
                // TODO: handle exception
                iv_recievedfile.setImageResource(R.drawable.download_icon);
                setProgressBar(subject3);
            }
        }
    } else {
        setProgressBar(subject3);
    }

}

From source file:com.mk4droid.IMC_Services.DatabaseHandler.java

/**
 *            Categories : Insert categories or update categories table
 *   //w w w  .  j  a v a2s .c o m
 * @return number of downloaded bytes 
 */
public int addUpdCateg(Context ctx) {

    int bdown = 0;

    String response = Download_Data.Download_Categories();

    if (response != null)
        bdown += response.length();

    try {
        JSONArray jArrCategs = new JSONArray(response);
        int NCateg = jArrCategs.length();

        if (!db.isOpen())
            db = this.getWritableDatabase();

        //--------- Create Helpers for Local db -----------------
        final InsertHelper iHelpC = new InsertHelper(db, TABLE_Categories);

        int c1 = iHelpC.getColumnIndex(KEY_CatID);
        int c2 = iHelpC.getColumnIndex(KEY_CatName);
        int c3 = iHelpC.getColumnIndex(KEY_CatIcon);
        int c4 = iHelpC.getColumnIndex(KEY_CatLevel);
        int c5 = iHelpC.getColumnIndex(KEY_CatParentID);
        int c6 = iHelpC.getColumnIndex(KEY_CatVisible);

        try {
            db.beginTransaction();
            Log.e("UPD", "Categs");
            for (int i = 0; i < NCateg; i++) {

                float prog = 100 * ((float) (i + 1)) / ((float) NCateg);

                ctx.sendBroadcast(
                        new Intent("android.intent.action.MAIN").putExtra("progressval", (int) (prog * 0.67)));

                JSONArray jArrData = new JSONArray(jArrCategs.get(i).toString());

                int CategID = jArrData.getInt(0);
                String CategName = jArrData.getString(1);
                int CategLevel = jArrData.getInt(2);
                int CategParentId = jArrData.getInt(3);
                String CategParams = jArrData.getString(4);

                JSONObject cpOb = new JSONObject(CategParams);
                String CategIconPath = cpOb.getString("image");

                String fullPath = Constants_API.COM_Protocol + Constants_API.ServerSTR
                        + Constants_API.remoteImages + CategIconPath;

                // Download icon
                byte[] CategIcon = Download_Data.Down_Image(fullPath);

                //------- Resize icon based on the device needs and store in db. --------------------
                Bitmap CategIconBM = BitmapFactory.decodeByteArray(CategIcon, 0, CategIcon.length);
                CategIconBM = Bitmap.createScaledBitmap(CategIconBM,
                        (int) ((float) Fragment_Map.metrics.densityDpi / 4.5),
                        (int) ((float) Fragment_Map.metrics.densityDpi / 4), true);

                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                CategIconBM.compress(Bitmap.CompressFormat.PNG, 100, stream);
                CategIcon = stream.toByteArray();
                //---------------------------------------------------------

                bdown += CategIcon.length;

                // Local db
                Cursor cursorC = db.rawQuery("SELECT " + KEY_CatID + "," + KEY_CatVisible + " FROM "
                        + TABLE_Categories + " WHERE " + KEY_CatID + "=" + Integer.toString(CategID), null);

                if (cursorC.moveToFirst()) { // Update 
                    iHelpC.prepareForReplace();
                    iHelpC.bind(c6, cursorC.getInt(1) == 1);
                } else {
                    iHelpC.prepareForInsert();
                    iHelpC.bind(c6, 1); // Insert
                }

                iHelpC.bind(c1, CategID);
                iHelpC.bind(c2, CategName);
                iHelpC.bind(c3, CategIcon);
                iHelpC.bind(c4, CategLevel);
                iHelpC.bind(c5, CategParentId);
                cursorC.close();

                iHelpC.execute();
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        } // TRY OF TRANSACTION 
    } catch (JSONException e1) {
        e1.printStackTrace();
        Log.e(Constants_API.TAG, TAG_Class + ": Categories update failed");
    } // TRY OF JSONARRAY

    return bdown;
}

From source file:com.htc.dotdesign.DrawingView.java

private void sharePicture() {
    if (mContext == null) {
        return;/*from   w  ww.  j  a  v a 2s  .  c  om*/
    }
    Bitmap bitmap = null;
    Bitmap scaledBmp = null;
    try {
        bitmap = handlePicture();
        scaledBmp = Bitmap.createScaledBitmap(bitmap, DotDesignConstants.SHARE_PHOTO_WIDTH,
                DotDesignConstants.SHARE_PHOTO_HEIGHT, false);
        DotDesignUtil.SaveImagetoExternal(scaledBmp, mContext);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (scaledBmp != null && !scaledBmp.isRecycled()) {
            scaledBmp.recycle();
            scaledBmp = null;
        }
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
    }
    File tmpFile = new File(mContext.getExternalFilesDir(null), DotDesignConstants.shareName);
    Intent shareintent = new Intent(Intent.ACTION_SEND);
    shareintent.setType("image/png");
    shareintent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(tmpFile));
    mContext.startActivity(Intent.createChooser(shareintent, "Share"));
}

From source file:org.yaoha.YaohaActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == SELECT_PICTURE) {
            selectedImageUri = data.getData();
            Bitmap tmpbitmap = null;/*from   w  w w. j  a  v  a2s.c  o m*/
            try {
                tmpbitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImageUri);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            int tmp_width = tmpbitmap.getWidth();
            int tmp_height = tmpbitmap.getHeight();
            Bitmap fav_bitmap = null;
            if (tmp_width < tmp_height) {
                fav_bitmap = Bitmap.createBitmap(tmpbitmap, 0, (tmp_height - tmp_width) / 2, tmp_width,
                        tmp_width);
            } else if (tmp_height < tmp_width) {
                fav_bitmap = Bitmap.createBitmap(tmpbitmap, (tmp_width - tmp_height) / 2, 0, tmp_height,
                        tmp_height);
            } else {
                fav_bitmap = tmpbitmap;
            }

            actualButton.setImageBitmap(Bitmap.createScaledBitmap(fav_bitmap, actualButton.getWidth() - 20,
                    actualButton.getHeight() - 20, false));
            if (actualButton.getId() == button_favorite_1.getId()) {
                writeDrawableToSD(actualButton.getDrawable(), "pic_fav_1.jpg");
            }
        }
    }
}

From source file:com.segma.trim.MainActivity.java

private Bitmap getSampleImage() {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;/*w  w w.ja  va2  s. c  o  m*/
    options.inScaled = false;
    int sample = getRandomSample();
    BitmapFactory.decodeResource(getResources(), sample, options);
    int imageHeight = options.outHeight;
    int imageWidth = options.outWidth;

    options.inJustDecodeBounds = false;
    if (true || imageHeight >= ImageProcessingViewHeight || imageWidth >= ImageProcessingViewWidth) {
        options.inSampleSize = calculateInSampleSize(options,
                ImageProcessingViewHeight * imageWidth / imageHeight, ImageProcessingViewHeight);
        return Bitmap.createScaledBitmap(
                decodeSampledBitmapFromResource(getResources(), sample,
                        ImageProcessingViewHeight * imageWidth / imageHeight, ImageProcessingViewHeight),
                ImageProcessingViewHeight * imageWidth / imageHeight, ImageProcessingViewHeight, true);
    }
    return BitmapFactory.decodeResource(getResources(), sample, options);
    //decodeSampledBitmapFromResource(getResources(), R.drawable.sample, ImageProcessingViewHeight * imageWidth / imageHeight, ImageProcessingViewHeight);
}

From source file:com.yohpapa.research.simplemusicplayer.PlaybackService.java

public void onEventAsync(NotificationPrepareEvent event) {
    Log.d(TAG, "onEventAsync: NotificationPrepareEvent");

    Context context = getApplicationContext();
    ContentResolver resolver = context.getContentResolver();
    Resources resources = context.getResources();

    Cursor trackCursor = null;/*  w  w w. jav a 2s .co  m*/
    Cursor albumCursor = null;
    try {
        Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, event.getTrackId());
        if (uri == null) {
            eventBus.post(new NotificationPreparedEvent(event.getTrackId(), null, null, null, null));
            return;
        }

        trackCursor = resolver
                .query(uri,
                        new String[] { MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST,
                                MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ALBUM_ID, },
                        null, null, null);

        if (trackCursor == null || !trackCursor.moveToFirst() || trackCursor.getCount() != 1) {
            eventBus.post(new NotificationPreparedEvent(event.getTrackId(), null, null, null, null));
            return;
        }

        String title = CursorHelper.getString(trackCursor, MediaStore.Audio.Media.TITLE);
        String artist = CursorHelper.getString(trackCursor, MediaStore.Audio.Media.ARTIST);
        String album = CursorHelper.getString(trackCursor, MediaStore.Audio.Media.ALBUM);
        long albumId = CursorHelper.getLong(trackCursor, MediaStore.Audio.Media.ALBUM_ID);
        Bitmap artwork = null;

        if (albumId != -1L) {
            uri = ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumId);
            if (uri == null) {
                eventBus.post(new NotificationPreparedEvent(event.getTrackId(), null, null, null, null));
                return;
            }
            albumCursor = resolver.query(uri, new String[] { MediaStore.Audio.Albums.ALBUM_ART, }, null, null,
                    null);

            if (albumCursor == null || !albumCursor.moveToFirst() || albumCursor.getCount() != 1) {
                eventBus.post(new NotificationPreparedEvent(event.getTrackId(), title, artist, album, null));
                return;
            }

            String artworkPath = CursorHelper.getString(albumCursor, MediaStore.Audio.Albums.ALBUM_ART);
            Bitmap buffer = BitmapFactory.decodeFile(artworkPath);
            artwork = Bitmap.createScaledBitmap(buffer,
                    resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
                    resources.getDimensionPixelSize(android.R.dimen.notification_large_icon_height), false);
            if (artwork != buffer) {
                buffer.recycle();
            }
        }

        eventBus.post(new NotificationPreparedEvent(event.getTrackId(), title, artist, album, artwork));

    } finally {
        if (trackCursor != null) {
            trackCursor.close();
        }
        if (albumCursor != null) {
            albumCursor.close();
        }
    }
}

From source file:com.android.leanlauncher.WidgetPreviewLoader.java

private static void renderBitmapIconOnPreview(Bitmap icon, Bitmap preview, int x, int y, int w, int h) {
    if (preview != null) {
        final Canvas c = new Canvas(preview);
        icon = Bitmap.createScaledBitmap(icon, w, h, false);
        c.drawBitmap(icon, x, y, null);/*  w  w  w.j a v  a  2 s  .  c o  m*/
        c.setBitmap(null);
    }
}

From source file:com.onesignal.GenerateNotification.java

private static Bitmap getLargeIcon(JSONObject gcmBundle) {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB)
        return null;

    Bitmap bitmap = getBitmapIcon(gcmBundle, "licon");
    if (bitmap == null)
        bitmap = getBitmapFromAssetsOrResourceName("ic_onesignal_large_icon_default");
    if (bitmap == null)
        bitmap = getBitmapFromAssetsOrResourceName("ic_gamethrive_large_icon_default");

    if (bitmap == null)
        return null;

    // Check to see if we need to shrink the bitmap to prevent cropping when
    // displayed.
    try {//from  w  w  w .ja v  a2s .  com
        int systemLargeIconHeight = (int) contextResources
                .getDimension(android.R.dimen.notification_large_icon_height);
        int systemLargeIconWidth = (int) contextResources
                .getDimension(android.R.dimen.notification_large_icon_width);
        int bitmapHeight = bitmap.getHeight();
        int bitmapWidth = bitmap.getWidth();

        if (bitmapWidth > systemLargeIconWidth || bitmapHeight > systemLargeIconHeight) {
            int newWidth = systemLargeIconWidth, newHeight = systemLargeIconHeight;
            if (bitmapHeight > bitmapWidth) {
                float ratio = (float) bitmapWidth / (float) bitmapHeight;
                newWidth = (int) (newHeight * ratio);
            } else if (bitmapWidth > bitmapHeight) {
                float ratio = (float) bitmapHeight / (float) bitmapWidth;
                newHeight = (int) (newWidth * ratio);
            }

            return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
        }
    } catch (Throwable t) {
    }

    return bitmap;
}