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.stikyhive.stikyhive.ChattingActivity.java

public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
    int width = image.getWidth();
    int height = image.getHeight();
    Log.i(TAG, " Widht .. " + width);
    Log.i(TAG, " Height .. " + height);
    float bitmapRatio = (float) width / (float) height;
    Log.i(TAG, " Bitmap Ratio" + bitmapRatio);
    if (bitmapRatio > 1) {
        width = maxSize;//from   w w  w  . jav a  2  s.c  om
        height = (int) (width / bitmapRatio);
    } else {
        height = maxSize;
        width = (int) (height * bitmapRatio);
    }
    Log.i(TAG, " Width .. <Image> .." + width);
    Log.i(TAG, " Height .. <Image> .." + height);
    return Bitmap.createScaledBitmap(image, width, height, true);
}

From source file:illab.nabal.NabalSimpleDemoActivity.java

/**
 * Fetch a photo attached to the current profile status from a remote URL 
 * /*from  w  w  w  .  j  ava  2s  . c om*/
 * @param remotePhotoUrl
 */
private final void fetchStatusThumbnailPhoto(final String remotePhotoUrl) {
    showSpinner();

    Operation<Delegate, Bitmap> bitmapOp = new Operation<Delegate, Bitmap>() {
        public void onResult(final Bitmap result) {
            if (result != null) {
                //Log.d(TAG, "############## remotePhotoUrl : " + remotePhotoUrl);
                //Log.d(TAG, "############## result.getWidth() : " + result.getWidth());
                //Log.d(TAG, "############## result.getheight() : " + result.getHeight());

                // determine screen width and height
                DisplayMetrics displaymetrics = new DisplayMetrics();
                getWindow().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
                int screenWidth = displaymetrics.widthPixels;
                int screenHeight = displaymetrics.heightPixels;
                int screenBiggerLength = (screenWidth > screenHeight) ? screenWidth : screenHeight;
                //Log.d(TAG, ">>>>>>>>>>>> screenWidth : " + screenWidth);
                //Log.d(TAG, ">>>>>>>>>>>> screenHeight : " + screenHeight);
                //Log.d(TAG, ">>>>>>>>>>>> screenBiggerLength : " + screenBiggerLength);

                // try to resize if the image is too big
                mTmpImgBitmap = result;
                if (mTmpImgBitmap.getWidth() > screenBiggerLength) {
                    int dstWidth = screenBiggerLength;
                    float ratio = (float) dstWidth / (float) mTmpImgBitmap.getWidth();
                    //Log.i(TAG, ">>>>>>>>>>>> ratio : " + ratio);
                    int dstHeight = (int) (mTmpImgBitmap.getHeight() * ratio);
                    //Log.i(TAG, ">>>>>>>>>>>> dstHeight : " + dstHeight);
                    mTmpImgBitmap = Bitmap.createScaledBitmap(mTmpImgBitmap, dstWidth, dstHeight, true);
                }

                //Log.d(TAG, "############## mTmpImgBitmap.getWidth() : " + mTmpImgBitmap.getWidth());
                //Log.d(TAG, "############## mTmpImgBitmap.getheight() : " + mTmpImgBitmap.getHeight());

                if (mCurrentSnsId == SocialNetwork.FACEBOOK) {
                    mFbBgBitmap = mTmpImgBitmap;
                } else if (mCurrentSnsId == SocialNetwork.TWITTER) {
                    mTwBgBitmap = mTmpImgBitmap;
                } else if (mCurrentSnsId == SocialNetwork.WEIBO) {
                    mWeBgBitmap = mTmpImgBitmap;
                }

                // set the image to background
                runOnUiThread(new Runnable() {
                    public void run() {
                        mBackground.setBackgroundDrawable(new BitmapDrawable(getResources(), mTmpImgBitmap));
                        mBackground.getBackground().setAlpha(STATUS_THUMBNAIL_BG_ALPHA);

                        // finally finishing up the status fetch job
                        mIsFetchingStatus = false;
                        toastProfileFetchResult();
                    }
                });
            }
        }

        public void onFail(Exception e) {
            mIsFetchingStatus = false;
            handleProfileFetchingError(e);
        }

        public void execute(Delegate networkDelegate) {
            if (StringHelper.isEmpty(remotePhotoUrl) == false) {
                networkDelegate.getBitmapFromUrl(this, remotePhotoUrl);
            }
        }
    };
    mOpAgent.carryOut(bitmapOp);
}

From source file:com.xmobileapp.rockplayer.LastFmAlbumArtImporter.java

/*******************************
 * /*from   w  w w . java  2  s.c  o  m*/
 * createSmallAlbumArt
 * 
 *******************************/
public void createSmallAlbumArt(String artistName, String albumName, boolean force) {
    /*
     * If small art already exists just return
     */
    String smallArtFileName = ((RockPlayer) context).FILEX_SMALL_ALBUM_ART_PATH + validateFileName(artistName)
            + " - " + validateFileName(albumName) + FILEX_FILENAME_EXTENSION;
    Log.i("CREATE", smallArtFileName);
    File smallAlbumArtFile = new File(smallArtFileName);
    if (!force && smallAlbumArtFile.exists() && smallAlbumArtFile.length() > 0) {
        return;
    }

    /*
     * Get path for existing Album art
     */
    String albumArtPath = getAlbumArtPath(artistName, albumName);

    /*
     * If album has art file create the small thumb from it 
     * otherwise do it from the cdcover resource
     */
    Bitmap smallBitmap = null;
    if (albumArtPath != null) {
        try {
            Log.i("SCALEBM", albumArtPath);
            //            BitmapFactory.Options opts = new BitmapFactory.Options();
            //            opts.inJustDecodeBounds = true;
            //            Bitmap bmTmp = BitmapFactory.decodeFile(albumArtPath, opts);
            //            Log.i("DBG", ""+opts.outWidth+" "+opts.outHeight);
            //            bmTmp.recycle();

            FileInputStream albumArtPathStream = new FileInputStream(albumArtPath);
            Bitmap bm = BitmapFactory.decodeStream(albumArtPathStream);
            smallBitmap = Bitmap.createScaledBitmap(bm, 120, 120, false);
            albumArtPathStream.close();
            bm.recycle();
        } catch (Exception e) {
            // TODO: failed to get from library
            //          show error
            //smallBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.albumart_mp_unknown);
            e.printStackTrace();
        } catch (Error err) {
            err.printStackTrace();
        }
    } else {
        //smallBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.albumart_mp_unknown);
        return;
    }

    try {
        if (smallAlbumArtFile != null)
            smallAlbumArtFile.createNewFile();
        else
            Log.i("DBG", "smallAlbumArtFile is null ?????");

        FileOutputStream smallAlbumArtFileStream = null;

        if (smallAlbumArtFile != null)
            smallAlbumArtFileStream = new FileOutputStream(smallAlbumArtFile);
        else
            Log.i("DBG", "smallAlbumArtFile is null ?????");

        if (smallBitmap != null && smallAlbumArtFileStream != null)
            smallBitmap.compress(Bitmap.CompressFormat.JPEG, 90, smallAlbumArtFileStream);
        else
            Log.i("DBG", "smallBitmap or smallAlbumArtFileStream is null ?????");

        if (smallAlbumArtFileStream != null)
            smallAlbumArtFileStream.close();
        else
            Log.i("DBG", "smallAlbumArtFileStream is null ?????");

        if (smallBitmap != null)
            smallBitmap.recycle();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

From source file:com.creativeongreen.imageeffects.MainActivity.java

public static Bitmap blurRenderScript(Bitmap bmImage, int radius, View v) {
    final float BITMAP_SCALE = 0.4f;
    final float BLUR_RADIUS = 7.5f;

    int width = Math.round(bmImage.getWidth() * BITMAP_SCALE);
    int height = Math.round(bmImage.getHeight() * BITMAP_SCALE);

    Bitmap inputBitmap = Bitmap.createScaledBitmap(bmImage, width, height, false);
    Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);

    RenderScript rs = RenderScript.create(v.getContext());
    Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
    Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
    //Allocation tmpIn = Allocation.createFromBitmap(rs, bmImage,
    //      Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT);
    //Allocation tmpOut = Allocation.createTyped(rs, tmpIn.getType());
    ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
    theIntrinsic.setRadius(radius);/*from   ww  w .  j a v  a2 s . c  o m*/
    theIntrinsic.setInput(tmpIn);
    theIntrinsic.forEach(tmpOut);
    tmpOut.copyTo(outputBitmap);

    return outputBitmap;
}

From source file:com.paramonod.kikos.MainActivity.java

public static Drawable createScaledIcon(Drawable id, int width, int height, Resources res) {
    Bitmap bitmap = ((BitmapDrawable) id).getBitmap();
    // Scale it to 50 x 50
    shop = new BitmapDrawable(res, Bitmap.createScaledBitmap(bitmap, width, height, true));
    return shop;//w w  w  .j ava  2 s .c  om
}

From source file:org.smilec.smile.student.CourseList.java

private Bitmap getBitmapFromCameraResult() {

    long id = -1;
    _act = this;/*from   w ww.ja v  a  2  s . c om*/
    // 1. Get Original id using m_cursor
    try {
        String[] proj = { MediaStore.Images.Media._ID };
        mcursor_for_camera = _act.managedQuery(imageUri, 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)

        int id_ColumnIndex = mcursor_for_camera.getColumnIndexOrThrow(MediaStore.Images.Media._ID);

        if (mcursor_for_camera.moveToFirst()) {
            id = mcursor_for_camera.getLong(id_ColumnIndex);

        } else {
            return null;
        }

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

    // 2. get Bitmap
    Bitmap b = null;
    try {
        Bitmap c = MediaStore.Images.Media.getBitmap(_act.getContentResolver(),
                Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id + ""));

        Log.d(APP_TAG, "Height" + c.getHeight() + " width= " + c.getWidth());

        // resize bitmap: code copied from
        // thinkandroid.wordpress.com/2009/12/25/resizing-a-bitmap/

        int target_width = 640; // 800, 360
        int target_height = 480; // 600, 240
        int w = c.getWidth();
        int h = c.getHeight();
        if ((w > target_width) || (h > target_height)) {
            b = Bitmap.createScaledBitmap(c, target_width, target_height, false);
        } else {
            b = c;
        }
    } catch (FileNotFoundException e) {
        Log.d(APP_TAG, "ERROR" + e);
    } catch (IOException e) {
        Log.d(APP_TAG, "ERROR" + e);
    }

    return b;

}

From source file:cx.ring.service.LocalService.java

public void updateTextNotifications() {
    Log.d(TAG, "updateTextNotifications()");

    for (Conversation c : conversations.values()) {
        TreeMap<Long, TextMessage> texts = c.getUnreadTextMessages();
        if (texts.isEmpty() || texts.lastEntry().getValue().isNotified()) {
            continue;
        } else/*from   ww  w.j  av  a  2s.c o  m*/
            notificationManager.cancel(c.notificationId);

        CallContact contact = c.getContact();
        if (c.notificationBuilder == null) {
            c.notificationBuilder = new NotificationCompat.Builder(getApplicationContext());
            c.notificationBuilder.setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setPriority(NotificationCompat.PRIORITY_HIGH).setDefaults(NotificationCompat.DEFAULT_ALL)
                    .setSmallIcon(R.drawable.ic_launcher).setContentTitle(contact.getDisplayName());
        }
        NotificationCompat.Builder noti = c.notificationBuilder;
        Intent c_intent = new Intent(Intent.ACTION_VIEW).setClass(this, ConversationActivity.class)
                .setData(Uri.withAppendedPath(ConversationActivity.CONTENT_URI, contact.getIds().get(0)));
        Intent d_intent = new Intent(ACTION_CONV_READ).setClass(this, LocalService.class)
                .setData(Uri.withAppendedPath(ConversationActivity.CONTENT_URI, contact.getIds().get(0)));
        noti.setContentIntent(PendingIntent.getActivity(this, new Random().nextInt(), c_intent, 0))
                .setDeleteIntent(PendingIntent.getService(this, new Random().nextInt(), d_intent, 0));

        if (contact.getPhoto() != null) {
            Resources res = getResources();
            int height = (int) res.getDimension(android.R.dimen.notification_large_icon_height);
            int width = (int) res.getDimension(android.R.dimen.notification_large_icon_width);
            noti.setLargeIcon(Bitmap.createScaledBitmap(contact.getPhoto(), width, height, false));
        }
        if (texts.size() == 1) {
            TextMessage txt = texts.firstEntry().getValue();
            txt.setNotified(true);
            noti.setContentText(txt.getMessage());
            noti.setStyle(null);
            noti.setWhen(txt.getTimestamp());
        } else {
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
            for (TextMessage s : texts.values()) {
                inboxStyle.addLine(Html.fromHtml("<b>"
                        + DateUtils.formatDateTime(this, s.getTimestamp(),
                                DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_ABBREV_ALL)
                        + "</b> " + s.getMessage()));
                s.setNotified(true);
            }
            noti.setContentText(texts.lastEntry().getValue().getMessage());
            noti.setStyle(inboxStyle);
            noti.setWhen(texts.lastEntry().getValue().getTimestamp());
        }
        notificationManager.notify(c.notificationId, noti.build());
    }
}

From source file:com.lifehackinnovations.siteaudit.FloorPlanActivity.java

public void assignonebitmap(int itemnumber, int type) {

    if (view.ITEMtype[itemnumber] == type) {
        view.ITEMbitmap[itemnumber] = Bitmap.createScaledBitmap(view.originaliconbitmap[type],
                view.originaliconbitmap[type].getWidth() * view.ITEMsizepercent[itemnumber] / 100,
                view.originaliconbitmap[type].getHeight() * view.ITEMsizepercent[itemnumber] / 100, true);
        view.iconbitmap[type] = view.ITEMbitmap[itemnumber];
    }//from   w ww  .ja  va 2  s  .  c o m
}

From source file:com.olacabs.customer.ui.TrackRideActivity.java

private Bitmap m13911a(int i, String str) {
    int i2 = 50;/*from w w w  .  j  a  v  a 2s.com*/
    Typeface createFromAsset = Typeface.createFromAsset(getAssets(), "OpenSans-Regular.ttf");
    int i3 = (int) getResources().getDisplayMetrics().scaledDensity;
    int i4 = i3 * 60;
    int i5 = i3 * 76;
    Config config = Config.ARGB_8888;
    if (i4 <= 0) {
        i4 = 50;
    }
    if (i5 > 0) {
        i2 = i5;
    }
    Bitmap createScaledBitmap = Bitmap
            .createScaledBitmap(BitmapFactoryInstrumentation.decodeResource(getResources(), i), i4, i2, true);
    Canvas canvas = new Canvas(createScaledBitmap);
    float f = (float) (i4 / 2);
    float f2 = (float) (i4 / 2);
    Paint paint = new Paint(1);
    paint.setColor(Color.parseColor("#d4db28"));
    paint.setStyle(Style.FILL);
    paint.setTextSize((float) (i3 * 18));
    paint.setTypeface(createFromAsset);
    if (str.length() == 3) {
        canvas.drawText(str, f - ((float) (i3 * 15)), f2, paint);
    } else if (str.length() == 2) {
        canvas.drawText(str, f - ((float) (i3 * 10)), f2, paint);
    } else if (str.length() == 1) {
        canvas.drawText(str, f - ((float) (i3 * 6)), f2, paint);
    }
    paint.setTextSize((float) (i3 * 16));
    canvas.drawText(" min ", f - ((float) (i3 * 18)), f2 + ((float) (i3 * 15)), paint);
    return createScaledBitmap;
}

From source file:com.skytree.epubtest.BookViewActivity.java

public void makeSearchBox() {
    int boxColor = Color.rgb(241, 238, 229);
    int innerBoxColor = Color.rgb(246, 244, 239);
    int inlineColor = Color.rgb(133, 105, 75);

    RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); // width,height
    searchBox = new SkyBox(this);
    searchBox.setBoxColor(boxColor);//  w  ww . j  a  v a 2s.c o  m
    searchBox.setArrowHeight(ps(25));
    searchBox.setArrowDirection(false);
    param.leftMargin = ps(50);
    param.topMargin = ps(400);
    param.width = ps(400);
    param.height = ps(300);
    searchBox.setLayoutParams(param);
    searchBox.setArrowDirection(false);

    searchEditor = new EditText(this);
    this.setFrame(searchEditor, ps(20), ps(20), ps(400 - 140), ps(50));
    searchEditor.setTextSize(15f);
    searchEditor.setEllipsize(TruncateAt.END);
    searchEditor.setBackgroundColor(innerBoxColor);
    Drawable icon = getResources().getDrawable(R.drawable.search2x);

    Bitmap bitmap = ((BitmapDrawable) icon).getBitmap();
    Drawable fd = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, ps(28), ps(28), true));
    searchEditor.setCompoundDrawablesWithIntrinsicBounds(fd, null, null, null);
    RoundRectShape rrs = new RoundRectShape(
            new float[] { ps(15), ps(15), ps(15), ps(15), ps(15), ps(15), ps(15), ps(15) }, null, null);
    SkyDrawable sd = new SkyDrawable(rrs, innerBoxColor, inlineColor, 2);
    searchEditor.setBackgroundDrawable(sd);
    searchEditor.setHint(getString(R.string.searchhint));
    searchEditor.setPadding(ps(20), ps(5), ps(10), ps(5));
    searchEditor.setLines(1);
    searchEditor.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
    searchEditor.setSingleLine();
    searchEditor.setOnEditorActionListener(new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_GO
                    || actionId == EditorInfo.IME_ACTION_SEARCH || actionId == EditorInfo.IME_ACTION_NEXT) {
                String key = searchEditor.getText().toString();
                if (key != null && key.length() > 1) {
                    showIndicator();
                    clearSearchBox(1);
                    makeFullScreen();
                    rv.searchKey(key);
                }
            }
            return false;
        }
    });
    searchBox.contentView.addView(searchEditor);

    Button cancelButton = new Button(this);
    this.setFrame(cancelButton, ps(290), ps(20), ps(90), ps(50));
    cancelButton.setText(getString(R.string.cancel));
    cancelButton.setId(3001);
    RoundRectShape crs = new RoundRectShape(
            new float[] { ps(5), ps(5), ps(5), ps(5), ps(5), ps(5), ps(5), ps(5) }, null, null);
    SkyDrawable cd = new SkyDrawable(crs, innerBoxColor, inlineColor, 2);
    cancelButton.setBackgroundDrawable(cd);
    cancelButton.setTextSize(12);
    cancelButton.setOnClickListener(listener);
    cancelButton.setOnTouchListener(new ButtonHighlighterOnTouchListener(cancelButton));

    searchBox.contentView.addView(cancelButton);

    searchScrollView = new ScrollView(this);
    RoundRectShape rvs = new RoundRectShape(
            new float[] { ps(5), ps(5), ps(5), ps(5), ps(5), ps(5), ps(5), ps(5) }, null, null);
    SkyDrawable rd = new SkyDrawable(rvs, innerBoxColor, inlineColor, 2);
    searchScrollView.setBackgroundDrawable(rd);
    this.setFrame(searchScrollView, ps(20), ps(100), ps(360), ps(200));
    this.searchBox.contentView.addView(searchScrollView);

    searchResultView = new LinearLayout(this);
    searchResultView.setOrientation(LinearLayout.VERTICAL);
    searchScrollView.addView(searchResultView,
            new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

    this.ePubView.addView(searchBox);
    this.hideSearchBox();
}