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:ch.ethz.twimight.net.opportunistic.ScanningService.java

private String getProcessedImage(String photoFileUri) {
    Bitmap bitmap = ImageLoader.getInstance().loadImageSync(photoFileUri);
    String encodedImage = null;/*www .  j  ava  2 s .  c  o  m*/
    if (bitmap != null) {
        // scale down large images
        if (bitmap.getHeight() > MAX_IMAGE_DIMENSIONS_PX || bitmap.getWidth() > MAX_IMAGE_DIMENSIONS_PX) {
            double shrinkFactor = ((double) MAX_IMAGE_DIMENSIONS_PX)
                    / Math.max(bitmap.getWidth(), bitmap.getHeight());
            bitmap = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * shrinkFactor),
                    (int) (bitmap.getHeight() * shrinkFactor), false);
        }
        ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayBitmapStream);
        byte[] bytes = byteArrayBitmapStream.toByteArray();
        encodedImage = Base64.encodeToString(bytes, Base64.DEFAULT);
    }
    return encodedImage;
}

From source file:com.bai.android.ui.OtherActivity.java

private Bitmap scaleBitmapToAvatarSize(Bitmap bitmapToResize) {
    int newHeight = TARGET_WIDTH_AND_HEIGHT;
    int newWidth = TARGET_WIDTH_AND_HEIGHT;
    if (bitmapToResize.getHeight() > bitmapToResize.getWidth()) {
        newWidth = (int) (bitmapToResize.getWidth() * newHeight / bitmapToResize.getHeight());
    } else {// w w w.  j  av a 2 s .  co  m
        newHeight = (int) (bitmapToResize.getHeight() * newWidth / bitmapToResize.getWidth());
    }
    return Bitmap.createScaledBitmap(bitmapToResize, newWidth, newHeight, false);
}

From source file:com.thejoshwa.ultrasonic.androidapp.util.Util.java

public static Bitmap scaleBitmap(Bitmap bitmap, int size) {
    return Bitmap.createScaledBitmap(bitmap, size, getScaledHeight(bitmap, size), true);
}

From source file:com.sim2dial.dialer.ChatFragment.java

private void uploadAndSendImage(final String filePath, final Bitmap image, final ImageSize size) {
    uploadLayout.setVisibility(View.VISIBLE);
    textLayout.setVisibility(View.GONE);

    uploadThread = new Thread(new Runnable() {
        @Override//from   w w w  .  java2  s.  c o m
        public void run() {
            Bitmap bm = null;
            String url = null;

            if (!uploadThread.isInterrupted()) {
                if (filePath != null) {
                    bm = BitmapFactory.decodeFile(filePath);
                    if (bm != null && size != ImageSize.REAL) {
                        int pixelsMax = size == ImageSize.SMALL ? SIZE_SMALL
                                : size == ImageSize.MEDIUM ? SIZE_MEDIUM : SIZE_LARGE;
                        if (bm.getWidth() > bm.getHeight() && bm.getWidth() > pixelsMax) {
                            bm = Bitmap.createScaledBitmap(bm, pixelsMax,
                                    (pixelsMax * bm.getHeight()) / bm.getWidth(), false);
                        } else if (bm.getHeight() > bm.getWidth() && bm.getHeight() > pixelsMax) {
                            bm = Bitmap.createScaledBitmap(bm, (pixelsMax * bm.getWidth()) / bm.getHeight(),
                                    pixelsMax, false);
                        }
                    }
                } else if (image != null) {
                    bm = image;
                }
            }

            // Rotate the bitmap if possible/needed, using EXIF data
            try {
                if (filePath != null) {
                    ExifInterface exif = new ExifInterface(filePath);
                    int pictureOrientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 0);
                    Matrix matrix = new Matrix();
                    if (pictureOrientation == 6) {
                        matrix.postRotate(90);
                    } else if (pictureOrientation == 3) {
                        matrix.postRotate(180);
                    } else if (pictureOrientation == 8) {
                        matrix.postRotate(270);
                    }
                    bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            if (bm != null) {
                bm.compress(CompressFormat.JPEG, COMPRESSOR_QUALITY, outStream);
            }

            if (!uploadThread.isInterrupted() && bm != null) {
                url = uploadImage(filePath, bm, COMPRESSOR_QUALITY, outStream.size());
                File file = new File(Environment.getExternalStorageDirectory(),
                        getString(R.string.temp_photo_name));
                file.delete();
            }

            if (!uploadThread.isInterrupted()) {
                final Bitmap fbm = bm;
                final String furl = url;
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        uploadLayout.setVisibility(View.GONE);
                        textLayout.setVisibility(View.VISIBLE);
                        progressBar.setProgress(0);
                        if (furl != null) {
                            sendImageMessage(furl, fbm);
                        } else {
                            Toast.makeText(getActivity(), getString(R.string.error), Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        }
    });
    uploadThread.start();
}

From source file:com.example.psumaps.MapView.java

private void drawMarker(LatLng point, String str) {
    // Creating an instance of MarkerOptions
    MarkerOptions markerOptions = new MarkerOptions();

    //IconGenerator tc = new IconGenerator(this);
    //Bitmap bmp = tc.makeIcon("hello");

    Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.bubble_white);// get the image same as your EditText

    int h = bitmap.getHeight() * 2;
    int w = bitmap.getWidth() * 2;

    bitmap = convertToMutable(bitmap);// converting the bitmap to mutable
    Bitmap incrsize = Bitmap.createScaledBitmap(bitmap, w, h, false);

    Canvas cs = new Canvas(incrsize);
    Paint pt = new Paint();
    pt.setColor(Color.BLACK);/*  w w  w . j  a  v a 2s  .  c  om*/
    //Typeface tf = Typeface.create("Helvetica",Typeface.BOLD);
    pt.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));

    String iam = str.toUpperCase(Locale.getDefault());

    pt.setTextSize(25);
    cs.drawText(iam, 0, iam.length(), (h / 2) + 10, (w / 2) / 2, pt);
    //pt.setColor(Color.RED);
    //cs.drawText("this is praki", 0, 13, h / 2, w / 3, pt);

    // Setting latitude and longitude for the marker
    markerOptions.position(point).title(str).icon(BitmapDescriptorFactory.fromBitmap(incrsize));

    // Adding marker on the Google Map
    map.addMarker(markerOptions);
}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MusicUtils.java

private static Bitmap getArtworkQuick(Context context, long album_id, int w, int h) {
    // NOTE: There is in fact a 1 pixel border on the right side in the ImageView
    // used to display this drawable. Take it into account now, so we don't have to
    // scale later.
    w -= 1;/*from  w  ww  .  j a  v a 2  s  .c  o m*/
    ContentResolver res = context.getContentResolver();
    Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
    if (uri != null) {
        ParcelFileDescriptor fd = null;
        try {
            fd = res.openFileDescriptor(uri, "r");
            int sampleSize = 1;

            // Compute the closest power-of-two scale factor
            // and pass that to sBitmapOptionsCache.inSampleSize, which will
            // result in faster decoding and better quality
            sBitmapOptionsCache.inJustDecodeBounds = true;
            BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache);
            int nextWidth = sBitmapOptionsCache.outWidth >> 1;
            int nextHeight = sBitmapOptionsCache.outHeight >> 1;
            while (nextWidth > w && nextHeight > h) {
                sampleSize <<= 1;
                nextWidth >>= 1;
                nextHeight >>= 1;
            }

            sBitmapOptionsCache.inSampleSize = sampleSize;
            sBitmapOptionsCache.inJustDecodeBounds = false;
            Bitmap b = BitmapFactory.decodeFileDescriptor(fd.getFileDescriptor(), null, sBitmapOptionsCache);

            if (b != null) {
                // finally rescale to exactly the size we need
                if (sBitmapOptionsCache.outWidth != w || sBitmapOptionsCache.outHeight != h) {
                    Bitmap tmp = Bitmap.createScaledBitmap(b, w, h, true);
                    // Bitmap.createScaledBitmap() can return the same bitmap
                    if (tmp != b)
                        b.recycle();
                    b = tmp;
                }
            }

            return b;
        } catch (FileNotFoundException e) {
        } finally {
            try {
                if (fd != null)
                    fd.close();
            } catch (IOException e) {
            }
        }
    }
    return null;
}

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

/*********************************
 * // ww  w . j av  a2 s.  c  om
 * creatAlbumArt
 * 
 *********************************/
public Bitmap createAlbumArt(String artistName, String albumName, Bitmap bm) {
    String fileName = ((RockPlayer) context).FILEX_ALBUM_ART_PATH + validateFileName(artistName) + " - "
            + validateFileName(albumName) + FILEX_FILENAME_EXTENSION;
    validateFileName(fileName);
    File albumArtFile = new File(fileName);

    try {
        /*
         * Set file output
         */

        albumArtFile.createNewFile();
        FileOutputStream albumArtFileStream = new FileOutputStream(albumArtFile);

        /*
          * Rescale/Crop the Bitmap
          */
        int MAX_SIZE = 480;
        float scaleFactor = (float) Math.max(1.0f,
                Math.min((float) bm.getWidth() / (float) MAX_SIZE, (float) bm.getHeight() / (float) MAX_SIZE));
        Log.i("CREATE", "" + scaleFactor);
        Bitmap albumArtBitmap = Bitmap.createScaledBitmap(bm,
                (int) Math.round((float) bm.getWidth() / scaleFactor),
                (int) Math.round((float) bm.getHeight() / scaleFactor), false);

        if (albumArtBitmap != null) {
            int dimension = Math.min(480, Math.min(albumArtBitmap.getHeight(), albumArtBitmap.getWidth()));
            Bitmap albumArtBitmapRescaled = Bitmap.createBitmap(albumArtBitmap,
                    (int) Math.floor((albumArtBitmap.getWidth() - dimension) / 2),
                    (int) Math.floor((albumArtBitmap.getHeight() - dimension) / 2), (int) dimension,
                    (int) dimension);

            FileOutputStream rescaledAlbumArtFileStream;
            rescaledAlbumArtFileStream = new FileOutputStream(albumArtFile);
            albumArtBitmapRescaled.compress(Bitmap.CompressFormat.JPEG, 96, rescaledAlbumArtFileStream);
            rescaledAlbumArtFileStream.close();
            if (albumArtBitmapRescaled != null)
                albumArtBitmapRescaled.recycle();

        } else {
            albumArtFile.delete();
        }
        if (albumArtBitmap != null)
            albumArtBitmap.recycle();
        return albumArtBitmap;
    } catch (Exception e) {
        e.printStackTrace();
        albumArtFile.delete();
        return null;
    } catch (Error err) {
        err.printStackTrace();
        return null;
    }

}

From source file:net.line2soft.preambul.views.SlippyMapActivity.java

/**
 * Adds a new marker to display on map//from ww  w.  j av a 2 s . co  m
 * @param loc The location of the marker
 * @param name The name of the marker
 * @param icon The associated icon
 */
public void addMarkerOnMap(GeoPoint loc, String name, Drawable icon) {
    icon = new BitmapDrawable(getResources(),
            Bitmap.createScaledBitmap(((BitmapDrawable) icon).getBitmap(), 56, 56, true));
    OverlayItem marker = new OverlayItem(loc, null, null, ItemizedOverlay.boundCenterBottom(icon));
    markers.put(name, marker);
    overlayPoiItemMarker.addItem(marker, null);
}

From source file:com.VVTeam.ManHood.Fragment.HistogramFragment.java

private List<PolarPlotData> plotDataForUserWithID(String userID, UsersData _usersData) {

    Bitmap orgBmp = BitmapFactory.decodeResource(getResources(), R.drawable.g_circle_b);

    float width = orgBmp.getWidth() * 50.0f / 100.0f;
    float height = width;

    PolarPlotData base = new PolarPlotData(0,
            Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.g_circle_b),
                    (int) width, (int) height, true),
            _usersData.basePositionOfUserWithID(userID));

    PolarPlotData mid = new PolarPlotData(2,
            Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.g_circle_m),
                    (int) width, (int) height, true),
            _usersData.midPositionOfUserWithID(userID));

    PolarPlotData upper = new PolarPlotData(4,
            Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.g_circle_s),
                    (int) width, (int) height, true),
            _usersData.upperPositionOfUserWithID(userID));

    PolarPlotData tip = new PolarPlotData(6,
            Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.g_circle_smaller),
                    (int) width, (int) height, true),
            _usersData.tipPositionOfUserWithID(userID));

    List<PolarPlotData> list = new ArrayList<PolarPlotData>();
    list.add(base);//from  w  ww. ja v a  2 s  .  co m
    list.add(mid);
    list.add(upper);
    list.add(tip);

    return list;
}

From source file:com.cordova.photo.CameraLauncher.java

/**
 * Return a scaled bitmap based on the target width and height
 *
 * @param imagePath/*w  w w  . j  a  v a 2 s . co  m*/
 * @return
 * @throws IOException 
 */
private Bitmap getScaledBitmap(String imageUrl) throws IOException {
    // If no new width or height were specified return the original bitmap
    if (this.targetWidth <= 0 && this.targetHeight <= 0) {
        return BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, activity));
    }

    // figure out the original width and height of the image
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, activity), null, options);

    //CB-2292: WTF? Why is the width null?
    if (options.outWidth == 0 || options.outHeight == 0) {
        return null;
    }

    // determine the correct aspect ratio
    int[] widthHeight = calculateAspectRatio(options.outWidth, options.outHeight);

    // Load in the smallest bitmap possible that is closest to the size we want
    options.inJustDecodeBounds = false;
    options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, this.targetWidth,
            this.targetHeight);
    Bitmap unscaledBitmap = BitmapFactory
            .decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, activity), null, options);
    if (unscaledBitmap == null) {
        return null;
    }

    return Bitmap.createScaledBitmap(unscaledBitmap, widthHeight[0], widthHeight[1], true);
}