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:nl.privacybarometer.privacyvandaag.activity.HomeActivity.java

private void selectDrawerItem(int position) {
    mCurrentDrawerPos = position;//from w  w w.j a v  a 2  s. c  o m
    Drawable mDrawable = null;
    Bitmap bitmap = null;
    BitmapDrawable mIcon = null;

    Uri newUri;
    boolean showFeedInfo = true;

    switch (position) {
    case SEARCH_DRAWER_POSITION:
        newUri = EntryColumns.SEARCH_URI(mEntriesFragment.getCurrentSearch());
        break;
    case 0:
        newUri = EntryColumns.ALL_ENTRIES_CONTENT_URI;
        //   Rescale the app-icon from the resources to the right size for use in the actionBar
        mDrawable = ContextCompat.getDrawable(this, R.drawable.ic_statusbar_pv);
        bitmap = ((BitmapDrawable) mDrawable).getBitmap();
        if (bitmap != null) {
            mIcon = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 36, 36, true));
        }
        break;
    case 1:
        newUri = EntryColumns.FAVORITES_CONTENT_URI;
        break;
    default:
        long feedOrGroupId = mDrawerAdapter.getItemId(position);
        mTitle = mDrawerAdapter.getItemName(position);
        if (mDrawerAdapter.isItemAGroup(position)) { // TODO: remove groups from the app. Not going to use this.
            newUri = EntryColumns.ENTRIES_FOR_GROUP_CONTENT_URI(feedOrGroupId);
        } else {
            // Get icons from resources instead of fetching favicons from websites on the internet.
            // Rescale the resources to the right size for use as drawer icon
            int mIconResourceId = mDrawerAdapter.getIconResourceId(position);
            if (mIconResourceId > 0) {
                mDrawable = ContextCompat.getDrawable(this, mIconResourceId);
                bitmap = ((BitmapDrawable) mDrawable).getBitmap();
                if (bitmap != null) {
                    mIcon = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 36, 36, true));
                }
            }
            //  If favicons from websites are used, they are feteched and stored as bitmaps in database
            /*
            byte[] iconBytes = mDrawerAdapter.getItemIcon(position);
            Bitmap bitmap = UiUtils.getScaledBitmap(iconBytes, 24);
            if (bitmap != null) {
               mIcon = new BitmapDrawable(getResources(), bitmap);
            }
            */
            newUri = EntryColumns.ENTRIES_FOR_FEED_CONTENT_URI(feedOrGroupId);
            showFeedInfo = false;
        }
        break;
    }
    if (!newUri.equals(mEntriesFragment.getUri())) {
        mEntriesFragment.setData(newUri, showFeedInfo);
    }

    mDrawerList.setItemChecked(position, true);

    // First run of the app => we open the drawer for you
    if (PrefUtils.getBoolean(PrefUtils.FIRST_OPEN, true)) {
        PrefUtils.putBoolean(PrefUtils.FIRST_OPEN, false);
        if (mDrawerLayout != null) {
            mDrawerLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mDrawerLayout.openDrawer(mLeftDrawer);
                }
            }, 500);
        }
        // Dialog popup that can be shown at first run after installation.
        /*
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.welcome_title);
        builder.show();
        */

        /* On first run after installation, try to add these feeds in database */
        FeedData.addPredefinedFeeds(this);
    } // end of settings on first run of the app.

    // Set title and icon in left drawer menu
    switch (mCurrentDrawerPos) {
    case SEARCH_DRAWER_POSITION:
        getSupportActionBar().setTitle(android.R.string.search_go);
        getSupportActionBar().setIcon(R.drawable.action_search);
        break;
    case 0:
        getSupportActionBar().setTitle(R.string.all);
        if (mIcon != null) {
            getSupportActionBar().setIcon(mIcon);
        } else {
            getSupportActionBar().setIcon(null);
        }
        break;
    case 1:
        getSupportActionBar().setTitle(R.string.favorites);
        getSupportActionBar().setIcon(R.drawable.rating_important);
        break;
    default:
        getSupportActionBar().setTitle(mTitle);
        if (mIcon != null) {
            getSupportActionBar().setIcon(mIcon);
        } else {
            getSupportActionBar().setIcon(null);
        }
        break;
    }

    // Put the good menu
    invalidateOptionsMenu();
}

From source file:com.imaginamos.taxisya.taxista.activities.RegisterDriverActivity.java

public boolean storageRegister() {
    Log.v(TAG, "storageRegister 1");

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    String registerName = sharedPref.getString("register_name", "");
    Log.v(TAG, "onActivityResult = status " + registerName);
    if (registerName != null && !TextUtils.isEmpty(registerName)) {
        name.setText(registerName);//w  ww . j  av  a  2s  .  c o  m
    }

    String registerIdentity = sharedPref.getString("register_identity", "");
    String registerLicense = sharedPref.getString("register_license", "");
    String registerEmail = sharedPref.getString("register_email", "");
    String registerPhone = sharedPref.getString("register_phone", "");
    String registerCellphone = sharedPref.getString("register_cellphone", "");
    String registerAddress = sharedPref.getString("register_address", "");
    String registerPassword = sharedPref.getString("register_password", "");
    String registerCarPlate = sharedPref.getString("register_car_plate", "");
    String registerCarBrand = sharedPref.getString("register_car_brand", "");
    String registerCarLine = sharedPref.getString("register_car_line", "");
    String registerCarMobileId = sharedPref.getString("register_car_mobile_id", "");
    String registerCarYear = sharedPref.getString("register_car_year", "");
    String registerCarCompany = sharedPref.getString("register_car_company", "");

    // photo
    String registerImage = sharedPref.getString("register_photo", "");
    if (registerImage != null && !TextUtils.isEmpty(registerImage)) {
        Bitmap bitmapImage = decodeBase64(registerImage);
        int nh = (int) (bitmapImage.getHeight() * (512.0 / bitmapImage.getWidth()));
        Bitmap scaled = Bitmap.createScaledBitmap(bitmapImage, 512, nh, true);
        photoImageView.setImageBitmap(scaled);
        mPhotoString = registerImage;
    }

    // doc1
    String registerDoc1 = sharedPref.getString("register_doc1", "");
    if (registerDoc1 != null && !TextUtils.isEmpty(registerDoc1)) {
        Bitmap bitmapImage = decodeBase64(registerDoc1);
        int nh = (int) (bitmapImage.getHeight() * (512.0 / bitmapImage.getWidth()));
        Bitmap scaled = Bitmap.createScaledBitmap(bitmapImage, 512, nh, true);
        documentImageView.setImageBitmap(scaled);
        mDocumentString = registerDoc1;
    }

    // doc2
    String registerDoc2 = sharedPref.getString("register_doc2", "");
    if (registerDoc2 != null && !TextUtils.isEmpty(registerDoc2)) {
        Bitmap bitmapImage = decodeBase64(registerDoc2);
        int nh = (int) (bitmapImage.getHeight() * (512.0 / bitmapImage.getWidth()));
        Bitmap scaled = Bitmap.createScaledBitmap(bitmapImage, 512, nh, true);
        document2ImageView.setImageBitmap(scaled);
        mDocument2String = registerDoc2;
    }

    // doc3
    String registerDoc3 = sharedPref.getString("register_doc3", "");
    if (registerDoc3 != null && !TextUtils.isEmpty(registerDoc3)) {
        Bitmap bitmapImage = decodeBase64(registerDoc3);
        int nh = (int) (bitmapImage.getHeight() * (512.0 / bitmapImage.getWidth()));
        Bitmap scaled = Bitmap.createScaledBitmap(bitmapImage, 512, nh, true);
        document3ImageView.setImageBitmap(scaled);
        mDocument3String = registerDoc3;
    }

    // doc4
    String registerDoc4 = sharedPref.getString("register_doc4", "");
    if (registerDoc4 != null && !TextUtils.isEmpty(registerDoc4)) {
        Bitmap bitmapImage = decodeBase64(registerDoc4);
        int nh = (int) (bitmapImage.getHeight() * (512.0 / bitmapImage.getWidth()));
        Bitmap scaled = Bitmap.createScaledBitmap(bitmapImage, 512, nh, true);
        document4ImageView.setImageBitmap(scaled);
        mDocument4String = registerDoc4;
    }

    if (registerIdentity != null && !TextUtils.isEmpty(registerIdentity)) {
        identity.setText(registerIdentity);
    }
    if (registerLicense != null && !TextUtils.isEmpty(registerLicense)) {
        license.setText(registerLicense);
    }
    if (registerEmail != null && !TextUtils.isEmpty(registerEmail)) {
        email.setText(registerEmail);
    }
    if (registerPhone != null && !TextUtils.isEmpty(registerPhone)) {
        phone.setText(registerPhone);
    }
    if (registerCellphone != null && !TextUtils.isEmpty(registerCellphone)) {
        cellphone.setText(registerCellphone);
    }
    if (registerAddress != null && !TextUtils.isEmpty(registerAddress)) {
        address.setText(registerAddress);
    }
    if (registerPassword != null && !TextUtils.isEmpty(registerPassword)) {
        pass.setText(registerPassword);
    }
    if (registerCarPlate != null && !TextUtils.isEmpty(registerCarPlate)) {
        carPlate.setText(registerCarPlate);
    }
    if (registerCarBrand != null && !TextUtils.isEmpty(registerCarBrand)) {
        carBrand.setText(registerCarBrand);
    }
    if (registerCarLine != null && !TextUtils.isEmpty(registerCarLine)) {
        carLine.setText(registerCarLine);
    }
    //if (registerCarMobileId != null && !TextUtils.isEmpty(registerCarMobileId)) { carMobileId.setText(registerCarMobileId); }
    if (registerCarYear != null && !TextUtils.isEmpty(registerCarYear)) {
        carYear.setText(registerCarYear);
    }
    if (registerCarCompany != null && !TextUtils.isEmpty(registerCarCompany)) {
        carCompany.setText(registerCarCompany);
    }

    Log.v(TAG, "storageRegister 2");

    return true;
}

From source file:com.beza.briver.fragments.ProfileFragment.java

private void onCaptureImageResult() {
    File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
    Bitmap bm = Helpers.decodeBitmapFromFile(file.getAbsolutePath());
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    if (bm.getHeight() > 3200 || bm.getWidth() > 3200) {
        Bitmap.createScaledBitmap(bm, bm.getWidth() / 4, bm.getHeight() / 4, false)
                .compress(Bitmap.CompressFormat.JPEG, 40, bytes);
    } else if (bm.getHeight() > 2560 || bm.getWidth() > 2560) {
        Bitmap.createScaledBitmap(bm, bm.getWidth() / 3, bm.getHeight() / 3, false)
                .compress(Bitmap.CompressFormat.JPEG, 40, bytes);
    } else if (bm.getHeight() > 1600 || bm.getWidth() > 1600) {
        Bitmap.createScaledBitmap(bm, bm.getWidth() / 2, bm.getHeight() / 2, false)
                .compress(Bitmap.CompressFormat.JPEG, 40, bytes);
    } else {//from ww w . j a va 2s .  co m
        bm.compress(Bitmap.CompressFormat.JPEG, 60, bytes);
    }
    hashMapTemp.put(ibPosition,
            Helpers.writeImageToExternalStorage(bytes, String.valueOf(ibPosition + "temp")));
    if (ibPosition == 0) {
        ibPhotoOne.setBackgroundDrawable(null);
        ibPhotoOne.setImageBitmap(Helpers.getCroppedBitmap(Helpers.getResizedBitmapToDisplay(bm, 120)));
    } else if (ibPosition == 1) {
        ibPhotoTwo.setBackgroundDrawable(null);
        ibPhotoTwo.setImageBitmap(Helpers.getCroppedBitmap(Helpers.getResizedBitmapToDisplay(bm, 120)));
    } else if (ibPosition == 2) {
        ibPhotoThree.setBackgroundDrawable(null);
        ibPhotoThree.setImageBitmap(Helpers.getCroppedBitmap(Helpers.getResizedBitmapToDisplay(bm, 120)));
    }
    imageChanged = true;
    imagePendingUpload = true;
}

From source file:org.appcelerator.titanium.TiBlob.java

@Kroll.method
public TiBlob imageAsResized(Number width, Number height) {
    Bitmap img = getImage();/* w w w .  j a  va 2 s . co  m*/
    if (img == null) {
        return null;
    }

    int dstWidth = width.intValue();
    int dstHeight = height.intValue();
    Bitmap imageResized = Bitmap.createScaledBitmap(img, dstWidth, dstHeight, true);
    return blobFromImage(imageResized);
}

From source file:com.example.android.wearable.mjpegviewwear.MainActivity.java

public void sendImage2Wear(Bitmap srcBmp) {
    if (mSendableImage) {

        Bitmap dstBmp = Bitmap.createBitmap(srcBmp, srcBmp.getWidth() / 2 - srcBmp.getHeight() / 2, 0,
                srcBmp.getHeight(), srcBmp.getHeight());

        Bitmap dstBmp2 = Bitmap.createScaledBitmap(dstBmp, 280, 280, false);

        sendImage(toAsset(dstBmp2));/* www .j  a v  a  2  s.co  m*/
    }
}

From source file:com.akop.bach.ImageCache.java

public Bitmap getBitmap(String imageUrl, boolean bypassCache, int resizeH, int resizeV) {
    File file = getCacheFile(imageUrl, null);

    // See if it's in the local cache 
    // (but only if not being forced to refresh)
    if (!bypassCache && file.canRead()) {
        if (App.getConfig().logToConsole())
            App.logv("Cache hit: " + file.getAbsolutePath());

        file.lastModified();//from  www  . ja va  2 s.  c  o m

        try {
            return BitmapFactory.decodeFile(file.getAbsolutePath());
        } catch (OutOfMemoryError e) {
            return null;
        }
    }

    // Fetch the image
    byte[] blob;
    int length;

    try {
        HttpClient client = new IgnorantHttpClient();
        HttpResponse resp = client.execute(new HttpGet(imageUrl));
        HttpEntity entity = resp.getEntity();

        if (entity == null)
            return null;

        InputStream stream = entity.getContent();
        if (stream == null)
            return null;

        try {
            if ((length = (int) entity.getContentLength()) <= 0)
                return null;

            blob = new byte[length];

            // Read the stream until nothing more to read
            for (int r = 0; r < length; r += stream.read(blob, r, length - r))
                ;
        } finally {
            stream.close();
            entity.consumeContent();
        }
    } catch (IOException e) {
        if (App.getConfig().logToConsole())
            e.printStackTrace();

        return null;
    }

    // if (file.canWrite())
    {
        FileOutputStream fos = null;

        try {
            fos = new FileOutputStream(file);

            if (resizeH > -1 || resizeV > -1) {
                Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, length);
                float aspectRatio = (float) bmp.getWidth() / (float) bmp.getHeight();

                int newWidth = (resizeH < 0) ? (int) ((float) resizeV * aspectRatio) : resizeH;
                int newHeight = (resizeV < 0) ? (int) ((float) resizeH / aspectRatio) : resizeV;

                Bitmap resized = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
                resized.compress(Bitmap.CompressFormat.PNG, 100, fos);

                return resized;
            } else {
                fos.write(blob);
            }

            if (App.getConfig().logToConsole())
                App.logv("Wrote to cache: " + file.getAbsolutePath());
        } catch (IOException e) {
            if (App.getConfig().logToConsole())
                e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    Bitmap bmp = null;

    try {
        bmp = BitmapFactory.decodeByteArray(blob, 0, length);
    } catch (Exception e) {
        if (App.getConfig().logToConsole())
            e.printStackTrace();
    }

    return bmp;
}

From source file:com.abc.driver.PersonalActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == CellSiteConstants.TAKE_USER_PORTRAIT
            || requestCode == CellSiteConstants.PICK_USER_PORTRAIT) {
        Uri uri = null;//  w  w  w  . ja  v  a 2s  . c o m
        if (requestCode == CellSiteConstants.TAKE_USER_PORTRAIT) {
            uri = imageUri;

        } else if (requestCode == CellSiteConstants.PICK_USER_PORTRAIT) {
            uri = data.getData();

        }

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            imageUri = Uri.fromFile(new File(filePath));
        } else // This is a bug, in some cases, some images like
        {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Toast.makeText(this, R.string.sdcard_occupied, Toast.LENGTH_SHORT).show();
                return;
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File tmpFile = new File(app.regUserPath + File.separator + "IMG_" + timeStamp + ".png");
            File srcFile = new File(uri.getPath());
            if (srcFile.exists()) {
                try {
                    Utils.copyFile(srcFile, tmpFile);
                    app.getUser().setProfileImageUrl(tmpFile.getAbsolutePath());
                } catch (Exception e) {
                    Toast.makeText(this, R.string.create_tmp_file_fail, Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                Log.d(TAG, "Logic error, should not come to here");
                Toast.makeText(this, R.string.file_not_found, Toast.LENGTH_SHORT).show();
                return;
            }

            imageUri = Uri.fromFile(tmpFile);
        }

        doCrop();
        Log.d(TAG, "onActivityResult PICK_PICTURE");

    } else if (requestCode == CellSiteConstants.CROP_PICTURE) {
        Log.d(TAG, "crop picture");
        // processFile();

        if (data != null) {
            Bundle extras = data.getExtras();
            Bitmap photo = extras.getParcelable("data");

            app.setPortaritBitmap(photo);
            mUserPortraitIv.setImageBitmap(photo);
            mUpdateImageTask = new UpdateImageTask();
            mUpdateImageTask.execute("" + app.getUser().getId(), Utils.bitmap2String(photo),
                    CellSiteConstants.UPDATE_USER_PORTRAIT_URL);

            isPortraitChanged = true;
        }
    } else if (requestCode == CellSiteConstants.TAKE_IDENTITY
            || requestCode == CellSiteConstants.PICK_IDENTITY) {

        Uri uri = null;
        if (requestCode == CellSiteConstants.TAKE_IDENTITY) {
            uri = imageUri;

        } else if (requestCode == CellSiteConstants.PICK_IDENTITY) {
            uri = data.getData();

        }

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            Log.d(TAG, "filePath =" + filePath);
            Log.d(TAG, "uri=" + uri.toString());
            imageUri = Uri.fromFile(new File(filePath));
        } else //
        {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Toast.makeText(this, R.string.sdcard_occupied, Toast.LENGTH_SHORT).show();
                return;
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File tmpFile = new File(app.regUserPath + File.separator + "IMG_" + timeStamp + ".png");
            File srcFile = new File(uri.getPath());
            if (srcFile.exists()) {
                try {
                    Utils.copyFile(srcFile, tmpFile);
                    app.getUser().setIdentityImageUrl(tmpFile.getAbsolutePath());
                } catch (Exception e) {
                    Toast.makeText(this, R.string.create_tmp_file_fail, Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                Log.d(TAG, "Logic error, should not come to here");
                Toast.makeText(this, R.string.file_not_found, Toast.LENGTH_SHORT).show();
                return;
            }

            imageUri = Uri.fromFile(tmpFile);
        }

        Bitmap tmpBmp = BitmapFactory.decodeFile(imageUri.getPath(), null);
        Bitmap scaledBmp = Bitmap.createScaledBitmap(tmpBmp, CellSiteConstants.IDENTITY_IMAGE_WIDTH,
                CellSiteConstants.IDENTITY_IMAGE_HEIGHT, false);

        mUserIdentityIv.setImageBitmap(scaledBmp);
        // s isChanged = true;
        mUpdateImageTask = new UpdateImageTask();
        mUpdateImageTask.execute("" + app.getUser().getId(), Utils.bitmap2String(scaledBmp),
                CellSiteConstants.UPDATE_USER_IDENTITY_URL);

    } else if (requestCode == CellSiteConstants.TAKE_DRIVER_LICENSE
            || requestCode == CellSiteConstants.PICK_DRIVER_LICENSE) {

        Uri uri = null;
        if (requestCode == CellSiteConstants.TAKE_DRIVER_LICENSE) {
            uri = imageUri;

        } else if (requestCode == CellSiteConstants.PICK_DRIVER_LICENSE) {
            uri = data.getData();

        }

        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();
            Log.d(TAG, "filePath =" + filePath);
            Log.d(TAG, "uri=" + uri.toString());
            imageUri = Uri.fromFile(new File(filePath));
        } else //
        {
            if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                Toast.makeText(this, R.string.sdcard_occupied, Toast.LENGTH_SHORT).show();
                return;
            }

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            File tmpFile = new File(app.regUserPath + File.separator + "IMG_" + timeStamp + ".png");
            File srcFile = new File(uri.getPath());
            if (srcFile.exists()) {
                try {
                    Utils.copyFile(srcFile, tmpFile);
                    app.getUser().setDriverLicenseImageUrl(tmpFile.getAbsolutePath());
                } catch (Exception e) {
                    Toast.makeText(this, R.string.create_tmp_file_fail, Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                Log.d(TAG, "Logic error, should not come to here");
                Toast.makeText(this, R.string.file_not_found, Toast.LENGTH_SHORT).show();
                return;
            }

            imageUri = Uri.fromFile(tmpFile);
        }

        Bitmap tmpBmp = BitmapFactory.decodeFile(imageUri.getPath(), null);
        Bitmap scaledBmp = Bitmap.createScaledBitmap(tmpBmp, CellSiteConstants.IDENTITY_IMAGE_WIDTH,
                CellSiteConstants.IDENTITY_IMAGE_HEIGHT, false);

        mUserDriverLicenseIv.setImageBitmap(scaledBmp);
        // s isChanged = true;
        mUpdateImageTask = new UpdateImageTask();
        mUpdateImageTask.execute("" + app.getUser().getId(), Utils.bitmap2String(scaledBmp),
                CellSiteConstants.UPDATE_DRIVER_LICENSE_URL);

    }
}

From source file:com.fsck.k9.helper.Utility.java

public static String getResizedImageFile(Context context, Uri uri, float multiplier) {
    File cacheDir = context.getCacheDir();
    File tempAttachmentsDirectory = new File(cacheDir.getPath() + RESIZED_ATTACHMENTS_TEMPORARY_DIRECTORY);
    tempAttachmentsDirectory.mkdirs();//from  w ww .  j  a  v  a 2 s.c  o  m

    File tempFile = null;
    Bitmap bitmap = null;
    Bitmap resized = null;
    FileOutputStream out = null;
    try {
        tempFile = File.createTempFile("TempResizedAttachment", null, tempAttachmentsDirectory);
        bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
        resized = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * multiplier),
                (int) (bitmap.getHeight() * multiplier), true);
        out = new FileOutputStream(tempFile);
        resized.compress(Bitmap.CompressFormat.PNG, 100, out);
    } catch (IOException e) {
        Timber.e(e, "Error while resizing image attachment");
        return "";
    } finally {
        IOUtils.closeQuietly(out);
    }

    return tempFile.getAbsolutePath();
}

From source file:com.polyvi.xface.extension.camera.XCameraExt.java

/**
 * ?/*from  w  ww. j a v  a2 s .  co m*/
 *
 * @param bitmap   ??.
 * @return Bitmap  ?.
 */
public Bitmap scaleBitmap(Bitmap bitmap) {
    int newWidth = mTargetWidth;
    int newHeight = mTargetHeight;
    int origWidth = bitmap.getWidth();
    int origHeight = bitmap.getHeight();

    // ?
    if (newWidth <= 0 && newHeight <= 0) {
        return bitmap;
    } else if (newWidth > 0 && newHeight <= 0) {
        newHeight = (newWidth * origHeight) / origWidth;
    } else if (newWidth <= 0 && newHeight > 0) {
        newWidth = (newHeight * origWidth) / origHeight;
    } else {
        double newRatio = newWidth / (double) newHeight;
        double origRatio = origWidth / (double) origHeight;

        if (origRatio > newRatio) {
            newHeight = (newWidth * origHeight) / origWidth;
        } else if (origRatio < newRatio) {
            newWidth = (newHeight * origWidth) / origHeight;
        }
    }
    return Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
}

From source file:com.example.android.navigationdrawer.QRCode.java

public void onQR(View v) {
    switch (v.getId()) {
    case R.id.button1:
        String qrInputText = MidiFile.readString;

        //Find screen size
        WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        Point point = new Point();
        display.getSize(point);/*from  w ww  .  j a  v  a 2 s . c  o  m*/
        int width = point.x;
        int height = point.y;
        int smallerDimension = width < height ? width : height;
        smallerDimension = smallerDimension * 3 / 4;
        //Encode with a QR Code image
        QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrInputText, null, Contents.Type.TEXT,
                BarcodeFormat.QR_CODE.toString(), smallerDimension);
        try {
            Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
            ImageView myImage = (ImageView) findViewById(R.id.imageView1);
            myImage.setImageBitmap(bitmap);

            // Get screen size
            Display display1 = this.getWindowManager().getDefaultDisplay();
            Point size = new Point();
            display1.getSize(size);
            int screenWidth = size.x;
            int screenHeight = size.y;

            // Get target image size
            Bitmap bitmap1 = qrCodeEncoder.encodeAsBitmap();
            int bitmapHeight = bitmap1.getHeight();
            int bitmapWidth = bitmap1.getWidth();

            // Scale the image down to fit perfectly into the screen
            // The value (250 in this case) must be adjusted for phone/tables displays
            while (bitmapHeight > (screenHeight - 250) || bitmapWidth > (screenWidth - 250)) {
                bitmapHeight = bitmapHeight / 2;
                bitmapWidth = bitmapWidth / 2;
            }

            // Create resized bitmap image
            BitmapDrawable resizedBitmap = new BitmapDrawable(this.getResources(),
                    Bitmap.createScaledBitmap(bitmap, bitmapWidth, bitmapHeight, false));

            // Create dialog
            Dialog dialog = new Dialog(this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.thumbnail);

            ImageView image = (ImageView) dialog.findViewById(R.id.imageview);

            // !!! Do here setBackground() instead of setImageDrawable() !!! //
            image.setBackground(resizedBitmap);

            // Without this line there is a very small border around the image (1px)
            // In my opinion it looks much better without it, so the choice is up to you.
            dialog.getWindow().setBackgroundDrawable(null);
            dialog.show();

        } catch (WriterException e) {
            e.printStackTrace();
        }
        break;
    }
}