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.c4mprod.utils.ImageManager.java

public static Bitmap shrinkBitmap(InputStream stream, int width, int height) {
    try {/*  w  w  w. j  a  v  a2s .co m*/
        // TODO check for a better solution for handling purgation
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
        Bitmap bitmap = BitmapFactory.decodeStream(stream, null, bmpFactoryOptions);
        computeRatio(width, height, bmpFactoryOptions);

        if (bitmap != null) {
            final int ratio = bmpFactoryOptions.inSampleSize;
            Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bmpFactoryOptions.outWidth / ratio,
                    bmpFactoryOptions.outHeight / ratio, false);
            if (scaledBitmap != bitmap) {
                bitmap.recycle();
            }
            return scaledBitmap;
        }
        return null;
    } catch (OutOfMemoryError e) {
        // Log.d("ImprovedImageDownloader.shrinkBitmap():", "memory !");
        return null;
    }
}

From source file:com.logilite.vision.camera.CameraLauncher.java

/**
 * Return a scaled bitmap based on the target width and height
 *
 * @param imagePath//  w ww . j  av a 2  s.  com
 * @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, cordova));
    }

    // figure out the original width and height of the image
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(FileHelper.getInputStreamFromUriString(imageUrl, cordova), 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, cordova), null, options);
    if (unscaledBitmap == null) {
        return null;
    }

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

From source file:com.miz.functions.MizLib.java

public static void resizeBitmapFileToCoverSize(Context c, String filepath) {

    final int mImageThumbSize = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);
    final int mImageThumbSpacing = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);

    WindowManager window = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);
    Display d = window.getDefaultDisplay();

    Point size = new Point();
    d.getSize(size);/*from w  w  w.ja  va2 s.  com*/

    final int numColumns = (int) Math.floor(Math.max(size.x, size.y) / (mImageThumbSize + mImageThumbSpacing));

    if (numColumns > 0) {
        final int columnWidth = (Math.max(size.x, size.y) / numColumns) - mImageThumbSpacing;

        int imageWidth = 0;

        if (columnWidth > 300)
            imageWidth = 500;
        else if (columnWidth > 240)
            imageWidth = 320;
        else if (columnWidth > 180)
            imageWidth = 240;
        else
            imageWidth = 180;

        if (new File(filepath).exists())
            try {
                Bitmap bm = decodeSampledBitmapFromFile(filepath, imageWidth, (int) (imageWidth * 1.5));
                bm = Bitmap.createScaledBitmap(bm, imageWidth, (int) (imageWidth * 1.5), true);
                FileOutputStream out = new FileOutputStream(filepath);
                bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.close();
                bm.recycle();
            } catch (Exception e) {
            }
    }
}

From source file:onion.chat.MainActivity.java

void showQR() {
    String name = db.getName();/* w w w . j  a  v  a2s .  c o  m*/
    String txt = "Its Ur's " + tor.getID() + " " + name;

    QRCode qr;

    try {
        //qr = Encoder.encode(txt, ErrorCorrectionLevel.H);
        qr = Encoder.encode(txt, ErrorCorrectionLevel.M);
    } catch (Exception ex) {
        throw new Error(ex);
    }

    ByteMatrix mat = qr.getMatrix();
    int width = mat.getWidth();
    int height = mat.getHeight();
    int[] pixels = new int[width * height];
    for (int y = 0; y < height; y++) {
        int offset = y * width;
        for (int x = 0; x < width; x++) {
            pixels[offset + x] = mat.get(x, y) != 0 ? Color.BLACK : Color.WHITE;
        }
    }
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);

    bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth() * 8, bitmap.getHeight() * 8, false);

    ImageView view = new ImageView(this);
    view.setImageBitmap(bitmap);

    int pad = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16,
            getResources().getDisplayMetrics());
    view.setPadding(pad, pad, pad, pad);

    Rect displayRectangle = new Rect();
    Window window = getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);
    int s = (int) (Math.min(displayRectangle.width(), displayRectangle.height()) * 0.9);
    view.setMinimumWidth(s);
    view.setMinimumHeight(s);
    new AlertDialog.Builder(this)
            //.setMessage(txt)
            .setView(view).show();
}

From source file:github.daneren2005.dsub.service.RESTMusicService.java

@Override
public Bitmap getCoverArt(Context context, MusicDirectory.Entry entry, int size, int saveSize,
        ProgressListener progressListener) throws Exception {

    // Synchronize on the entry so that we don't download concurrently for the same song.
    synchronized (entry) {

        // Use cached file, if existing.
        Bitmap bitmap = FileUtil.getAlbumArtBitmap(context, entry, size);
        if (bitmap != null) {
            return bitmap;
        }//from ww  w .ja  v  a  2  s.c o  m

        String url = Util.getRestUrl(context, "getCoverArt");

        InputStream in = null;
        try {
            List<String> parameterNames = Arrays.asList("id", "size");
            List<Object> parameterValues = Arrays.<Object>asList(entry.getCoverArt(), saveSize);
            HttpEntity entity = getEntityForURL(context, url, null, parameterNames, parameterValues,
                    progressListener);
            in = entity.getContent();

            // If content type is XML, an error occured.  Get it.
            String contentType = Util.getContentType(entity);
            if (contentType != null && contentType.startsWith("text/xml")) {
                new ErrorParser(context).parse(new InputStreamReader(in, Constants.UTF_8));
                return null; // Never reached.
            }

            byte[] bytes = Util.toByteArray(in);

            File albumDir = FileUtil.getAlbumDirectory(context, entry);
            if (albumDir.exists()) {
                OutputStream out = null;
                try {
                    out = new FileOutputStream(FileUtil.getAlbumArtFile(albumDir));
                    out.write(bytes);
                } finally {
                    Util.close(out);
                }
            }

            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            if (size != saveSize) {
                bitmap = Bitmap.createScaledBitmap(bitmap, size, size, true);
            }
            return bitmap;

        } finally {
            Util.close(in);
        }
    }
}

From source file:com.undatech.opaque.RemoteCanvas.java

public void disconnectAndCleanUp() {
    stayConnected = false;//from ww w. ja va  2  s . co m

    if (keyboard != null) {
        // Tell the server to release any meta keys.
        keyboard.clearOnScreenMetaState();
        keyboard.keyEvent(0, new KeyEvent(KeyEvent.ACTION_UP, 0));
    }

    if (spicecomm != null)
        spicecomm.close();

    if (handler != null) {
        handler.removeCallbacksAndMessages(null);
    }

    if (clipboardMonitorTimer != null) {
        clipboardMonitorTimer.cancel();
        // Occasionally causes a NullPointerException
        //clipboardMonitorTimer.purge();
        clipboardMonitorTimer = null;
    }

    clipboardMonitor = null;
    clipboard = null;

    try {
        if (myDrawable != null && myDrawable.bitmap != null) {
            String location = settings.getFilename();
            FileOutputStream out = new FileOutputStream(getContext().getFilesDir() + "/" + location + ".png");
            Bitmap tmp = Bitmap.createScaledBitmap(myDrawable.bitmap, 360, 300, true);
            myDrawable.bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.close();
            tmp.recycle();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    disposeDrawable();
}

From source file:com.vishwa.pinit.MainActivity.java

private void createMarkerAtLocation(final double latitude, final double longitude, final Note note) {
    if (mReverseNoteStore.get(note.getNoteId()) == null) {
        Bitmap balloonBackground = BitmapFactory.decodeResource(getResources(), R.drawable.balloon_background);
        Bitmap userPhoto = null;//  w w  w  .j  av  a 2 s  .  c o m

        if (note.getNoteCreator().equals(mCurrentUsername)) {
            balloonBackground = Bitmap.createScaledBitmap(balloonBackground, 87, 94, false);
            userPhoto = Bitmap.createScaledBitmap(mUserPhotoThumbnail, 75, 71, false);

            Canvas canvas = new Canvas(balloonBackground);
            canvas.drawBitmap(balloonBackground, 0, 0, null);
            canvas.drawBitmap(userPhoto, 6, 6, null);

            addMarkerToMap(note, balloonBackground, latitude, longitude);
        } else {
            if (mMemoryCache.get(note.getNoteCreator()) != null) {

                balloonBackground = Bitmap.createScaledBitmap(balloonBackground, 87, 94, false);
                userPhoto = Bitmap.createScaledBitmap(mMemoryCache.get(note.getNoteCreator()), 75, 71, false);

                Canvas canvas = new Canvas(balloonBackground);
                canvas.drawBitmap(balloonBackground, 0, 0, null);
                canvas.drawBitmap(userPhoto, 6, 6, null);

                addMarkerToMap(note, balloonBackground, latitude, longitude);
            } else {
                ParseQuery query = ParseUser.getQuery();
                query.whereEqualTo("username", note.getNoteCreator());
                query.getFirstInBackground(new GetCallback() {

                    @Override
                    public void done(ParseObject object, ParseException e) {
                        if (e == null) {
                            ParseObject noteCreator = object;
                            if (noteCreator.getBoolean("isDefaultPhoto")) {
                                Bitmap balloonBackground = BitmapFactory.decodeResource(getResources(),
                                        R.drawable.balloon_background);
                                Bitmap userPhoto = null;
                                balloonBackground = Bitmap.createScaledBitmap(balloonBackground, 87, 94, false);
                                userPhoto = Bitmap.createScaledBitmap(mMemoryCache.get("defaultPhoto"), 75, 71,
                                        false);
                                note.setNoteCreatorHasDefaultPhoto(true);

                                Canvas canvas = new Canvas(balloonBackground);
                                canvas.drawBitmap(balloonBackground, 0, 0, null);
                                canvas.drawBitmap(userPhoto, 6, 6, null);

                                addMarkerToMap(note, balloonBackground, latitude, longitude);
                            } else {
                                ParseFile userPhotoFile = noteCreator.getParseFile("profilePhotoThumbnail");
                                userPhotoFile.getDataInBackground(new GetDataCallback() {

                                    @Override
                                    public void done(byte[] data, ParseException e) {
                                        if (e == null) {
                                            Bitmap balloonBackground = BitmapFactory.decodeResource(
                                                    getResources(), R.drawable.balloon_background);

                                            Bitmap userPhoto = BitmapFactory.decodeByteArray(data, 0,
                                                    data.length);
                                            mMemoryCache.put(note.getNoteCreator(), userPhoto);

                                            balloonBackground = Bitmap.createScaledBitmap(balloonBackground, 87,
                                                    94, false);
                                            userPhoto = Bitmap.createScaledBitmap(userPhoto, 75, 71, false);

                                            Canvas canvas = new Canvas(balloonBackground);
                                            canvas.drawBitmap(balloonBackground, 0, 0, null);
                                            canvas.drawBitmap(userPhoto, 6, 6, null);

                                            addMarkerToMap(note, balloonBackground, latitude, longitude);
                                        } else {
                                            Toast.makeText(getApplicationContext(), "Photo load failed",
                                                    Toast.LENGTH_LONG).show();
                                            PinItUtils.createAlert("This is embarrassing",
                                                    "Please log out and login again", MainActivity.this);
                                        }
                                    }
                                });
                            }
                        } else {
                            Toast.makeText(getApplicationContext(), note.getNoteCreator(), Toast.LENGTH_LONG)
                                    .show();
                            PinItUtils.createAlert("This is embarrassing", "Please log out and login again",
                                    MainActivity.this);
                        }
                    }
                });
            }
        }
    }
}

From source file:com.mattprecious.notisync.service.SecondaryService.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private Bitmap resizePhoto(Bitmap photo) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        if (photo != null) {
            final int idealIconHeight = getResources()
                    .getDimensionPixelSize(android.R.dimen.notification_large_icon_height);
            final int idealIconWidth = getResources()
                    .getDimensionPixelSize(android.R.dimen.notification_large_icon_width);
            if (photo.getHeight() < idealIconHeight) {
                photo = Bitmap.createScaledBitmap(photo, idealIconWidth, idealIconHeight, true);
            }//w  w  w. ja va2 s  . co  m
        }
    }

    return photo;
}

From source file:com.mobantica.DriverItRide.activities.ActivityProfile.java

private void previewCapturedImage() {
    try {/*from   w  ww  .  ja v  a 2  s  .co m*/
        Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), ChnagedUri);
        if (bitmap != null) {
            ExifInterface ei = null;
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    InputStream in = getContentResolver().openInputStream(ChnagedUri);
                    ei = new ExifInterface(in);
                } else {
                    ei = new ExifInterface(ChnagedUri.getPath());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ei != null) {
                int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);
                switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    bitmap = rotateImage(bitmap, 90);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    bitmap = rotateImage(bitmap, 180);
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    bitmap = rotateImage(bitmap, 270);
                    break;
                }
            }

            Bitmap imageBitmap;
            imageBitmap = Bitmap.createScaledBitmap(AppUtils.resizeAndCropCenter(bitmap, 250, true), 250, 250,
                    false);
            img_profile_square.setImageBitmap(imageBitmap);

            imagebaseProfilephoto = Generic.convertBitmapToByteStrem(imageBitmap);
            task = new ActivityProfile.UpdateProfilePhotoTask();
            task.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
        }
    } catch (IOException e) {
        e.printStackTrace();
        //Set default image here
    }
}

From source file:com.rnd.snapsplit.view.OcrCaptureFragment.java

public Bitmap byteStreamToBitmap(byte[] data) {
    int imageWidth = mCameraSource.getPreviewSize().getWidth();
    int imageHeight = mCameraSource.getPreviewSize().getHeight();
    //            YuvImage yuvimage=new YuvImage(data, ImageFormat.NV16, previewSizeW, previewSizeH, null);
    //            ByteArrayOutputStream baos = new ByteArrayOutputStream();
    //            yuvimage.compressToJpeg(new Rect(0, 0, previewSizeW, previewSizeH), 80, baos);
    //            byte[] jdata = baos.toByteArray();

    Bitmap bitmap = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
    int numPixels = imageWidth * imageHeight;

    // the buffer we fill up which we then fill the bitmap with
    IntBuffer intBuffer = IntBuffer.allocate(imageWidth * imageHeight);
    // If you're reusing a buffer, next line imperative to refill from the start,
    // if not good practice
    intBuffer.position(0);/*from   www . ja v a 2s  .  c  o  m*/

    // Set the alpha for the image: 0 is transparent, 255 fully opaque
    final byte alpha = (byte) 255;

    // Get each pixel, one at a time
    for (int y = 0; y < imageHeight; y++) {
        for (int x = 0; x < imageWidth; x++) {
            // Get the Y value, stored in the first block of data
            // The logical "AND 0xff" is needed to deal with the signed issue
            int Y = data[y * imageWidth + x] & 0xff;

            // Get U and V values, stored after Y values, one per 2x2 block
            // of pixels, interleaved. Prepare them as floats with correct range
            // ready for calculation later.
            int xby2 = x / 2;
            int yby2 = y / 2;

            // make this V for NV12/420SP
            float U = (float) (data[numPixels + 2 * xby2 + yby2 * imageWidth] & 0xff) - 128.0f;

            // make this U for NV12/420SP
            float V = (float) (data[numPixels + 2 * xby2 + 1 + yby2 * imageWidth] & 0xff) - 128.0f;

            // Do the YUV -> RGB conversion
            float Yf = 1.164f * ((float) Y) - 16.0f;
            int R = (int) (Yf + 1.596f * V);
            int G = (int) (Yf - 0.813f * V - 0.391f * U);
            int B = (int) (Yf + 2.018f * U);

            // Clip rgb values to 0-255
            R = R < 0 ? 0 : R > 255 ? 255 : R;
            G = G < 0 ? 0 : G > 255 ? 255 : G;
            B = B < 0 ? 0 : B > 255 ? 255 : B;

            // Put that pixel in the buffer
            intBuffer.put(alpha * 16777216 + R * 65536 + G * 256 + B);
        }
    }

    // Get buffer ready to be read
    intBuffer.flip();

    // Push the pixel information from the buffer onto the bitmap.
    bitmap.copyPixelsFromBuffer(intBuffer);

    Matrix matrix = new Matrix();
    matrix.postRotate(90);
    Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, imageWidth, imageHeight, true);
    Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(),
            scaledBitmap.getHeight(), matrix, true);
    return rotatedBitmap;
}