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.example.user.lstapp.CreatePlaceFragment.java

private byte[] processPhoto(byte[] data) {
    Log.d(TAG, "picture processing");
    Bitmap originalImg = BitmapFactory.decodeByteArray(data, 0, data.length);

    //resize image
    Bitmap resizedImg = Bitmap.createScaledBitmap(originalImg, (int) (originalImg.getWidth() * 0.2),
            (int) (originalImg.getHeight() * 0.2), true);
    //rotate image to match view for user
    Matrix matrix = new Matrix();
    matrix.postRotate(90);/* w w  w  . ja v  a2 s. c om*/
    Bitmap rotatedImg = Bitmap.createBitmap(resizedImg, 0, 0, resizedImg.getWidth(), resizedImg.getHeight(),
            matrix, true);
    //convert to byte format for sending to server
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    rotatedImg.compress(Bitmap.CompressFormat.PNG, 100, stream);
    return stream.toByteArray();
}

From source file:es.uma.lcc.tasks.EncryptionUploaderTask.java

private void displayEncryptedImage(String path) {
    ImageView imageView = (ImageView) mMainActivity.findViewById(R.id.imageView);
    imageView.setVisibility(ImageView.VISIBLE);

    BitmapFactory.Options options = new BitmapFactory.Options();
    Bitmap bmp = BitmapFactory.decodeFile(path, options);
    int w = options.outWidth;
    int h = options.outHeight;

    if (w >= 2048 || h >= 2048) {
        double factor = (w > h ? 2048.0 / w : 2048.0 / h);
        imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, (int) (factor * w), (int) (factor * h), false));
    } else {//from w  w w .j  a  v a 2s  . c  o m
        imageView.setImageBitmap(bmp);
    }
}

From source file:de.mrapp.android.util.BitmapUtil.java

/**
 * Resizes a bitmap to a specific width and height. If the ratio between width and height
 * differs from the bitmap's original ratio, the bitmap is stretched.
 *
 * @param bitmap/*from  w ww.  j  a va2s.  c  o m*/
 *         The bitmap, which should be resized, as an instance of the class {@link Bitmap}. The
 *         bitmap may not be null
 * @param width
 *         The width, the bitmap should be resized to, as an {@link Integer} value in pixels.
 *         The width must be at least 1
 * @param height
 *         The height, the bitmap should be resized to, as an {@link Integer} value in pixels.
 *         The height must be at least 1
 * @return The resized bitmap as an instance of the class {@link Bitmap}
 */
public static Bitmap resize(@NonNull final Bitmap bitmap, final int width, final int height) {
    ensureNotNull(bitmap, "The bitmap may not be null");
    ensureAtLeast(width, 1, "The width must be at least 1");
    ensureAtLeast(height, 1, "The height must be at least 1");
    return Bitmap.createScaledBitmap(bitmap, width, height, false);
}

From source file:com.box.myview.MyTopSnackBar.TSnackbar.java

/**
 * @param resource_id image id//w w  w . j a  va2s  .c o  m
 * @param width       image width
 * @param height      image height
 * @return
 */
public TSnackbar addIcon(int resource_id, int width, int height) {
    final TextView tv = mView.getMessageView();
    if (width > 0 || height > 0) {
        tv.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(Bitmap.createScaledBitmap(
                ((BitmapDrawable) (mContext.getResources().getDrawable(resource_id))).getBitmap(), width,
                height, true)), null, null, null);
    } else {
        addIcon(resource_id);
    }
    return this;
}

From source file:com.yyjlr.tickets.viewutils.snakebar.TSnackbar.java

/**
 * @param resource_id image id//from  w  w  w . j  av  a2  s .  c  o m
 * @param width       image width
 * @param height      image height
 * @return
 */
public TSnackbar addIcon(int resource_id, int width, int height) {
    final TextView tv = mView.getMessageView();
    if (resource_id != -1) {
        if (width > 0 || height > 0) {
            tv.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(Bitmap.createScaledBitmap(
                    ((BitmapDrawable) (mContext.getResources().getDrawable(resource_id))).getBitmap(), width,
                    height, true)), null, null, null);
        } else {
            addIcon(resource_id);
        }
    }
    return this;
}

From source file:com.maass.android.imgur_uploader.ImgurUpload.java

/**
 * This method uploads create a thumbnail for local use from the uri
 * /*from   w w  w .ja  va  2 s.  c  o m*/
 * @param uri
 *            image location
 */
private void createThumbnail(final Uri uri) {
    Log.i(this.getClass().getName(), "in createThumbnail(Uri)");
    try {
        final Bitmap image = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
        int height = image.getHeight();
        int width = image.getWidth();
        if (width > height) {
            height = height * THUMBNAIL_MAX_SIZE / width;
            width = THUMBNAIL_MAX_SIZE;
        } else {
            width = width * THUMBNAIL_MAX_SIZE / height;
            height = THUMBNAIL_MAX_SIZE;
        }
        final Bitmap resizedBitmap = Bitmap.createScaledBitmap(image, width, height, false);

        final FileOutputStream f = openFileOutput(mImgurResponse.get("image_hash") + THUMBNAIL_POSTFIX,
                Context.MODE_PRIVATE);

        resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 75, f);

    } catch (final IOException e1) {
        Log.e(this.getClass().getName(), "Error creating thumbnail", e1);
    }
}

From source file:com.twitterdev.rdio.app.RdioApp.java

private void next(final boolean manualPlay) {
    if (player != null) {
        player.stop();/*from  ww w  .j a  v a  2 s  . co  m*/
        player.release();
        player = null;
    }

    final Track track = trackQueue.poll();
    if (trackQueue.size() < 3) {
        Log.i(TAG, "Track queue depleted, loading more tracks");
        LoadMoreTracks();
    }

    if (track == null) {
        Log.e(TAG, "Track is null!  Size of queue: " + trackQueue.size());
        return;
    }

    // Load the next track in the background and prep the player (to start buffering)
    // Do this in a bkg thread so it doesn't block the main thread in .prepare()
    AsyncTask<Track, Void, Track> task = new AsyncTask<Track, Void, Track>() {
        @Override
        protected Track doInBackground(Track... params) {
            Track track = params[0];
            final String trackName = track.artistName;
            final String artist = track.trackName;
            try {
                player = rdio.getPlayerForTrack(track.key, null, manualPlay);
                player.prepare();
                player.setOnCompletionListener(new OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        next(false);
                    }
                });
                player.start();
                new getSearch().execute(track.trackName);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        TextView a = (TextView) findViewById(R.id.artist);
                        //a.setText(artist);
                        TextView t = (TextView) findViewById(R.id.track);
                        //t.setText(trackName);
                    }
                });

            } catch (Exception e) {
                Log.e("Test", "Exception " + e);
            }
            return track;
        }

        @Override
        protected void onPostExecute(Track track) {
            updatePlayPause(true);
        }
    };
    task.execute(track);

    // Fetch album art in the background and then update the UI on the main thread
    AsyncTask<Track, Void, Bitmap> artworkTask = new AsyncTask<Track, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(Track... params) {
            Track track = params[0];
            try {
                String artworkUrl = track.albumArt.replace("square-200", "square-600");
                Log.i(TAG, "Downloading album art: " + artworkUrl);
                Bitmap bm = null;
                try {
                    URL aURL = new URL(artworkUrl);
                    URLConnection conn = aURL.openConnection();
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    bm = BitmapFactory.decodeStream(bis);
                    bis.close();
                    is.close();
                } catch (IOException e) {
                    Log.e(TAG, "Error getting bitmap", e);
                }
                return bm;
            } catch (Exception e) {
                Log.e(TAG, "Error downloading artwork", e);
                return null;
            }
        }

        @Override
        protected void onPostExecute(Bitmap artwork) {
            if (artwork != null) {
                int imageWidth = artwork.getWidth();
                int imageHeight = artwork.getHeight();
                DisplayMetrics dimension = new DisplayMetrics();
                getWindowManager().getDefaultDisplay().getMetrics(dimension);
                int newWidth = dimension.widthPixels;

                float scaleFactor = (float) newWidth / (float) imageWidth;
                int newHeight = (int) (imageHeight * scaleFactor);

                artwork = Bitmap.createScaledBitmap(artwork, newWidth, newHeight, true);
                //albumArt.setImageBitmap(bitmap);

                albumArt.setAdjustViewBounds(true);
                albumArt.setImageBitmap(artwork);

            } else
                albumArt.setImageResource(R.drawable.blank_album_art);
        }
    };
    artworkTask.execute(track);

    //Toast.makeText(this, String.format(getResources().getString(R.string.now_playing), track.trackName, track.albumName, track.artistName), Toast.LENGTH_LONG).show();
}

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

private void outgoingImage(String numb) {
    Log.setLogLevel(6);//from  ww w.  j  a v a 2s. c  o m
    Log.d("outgoingImage", "call");
    iv_recievedfile = (ImageView) v.findViewById(R.id.iv_recievedfile);

    if (isimagemsginit(subject)) {
        pb_uploading.setVisibility(ProgressBar.VISIBLE);
    } else {
        pb_uploading.setVisibility(ProgressBar.GONE);
    }

    if (isvideoMsg(subject)) {
        text_view.setVisibility(TextView.GONE);
        iv_recievedfile.setVisibility(ImageView.VISIBLE);
        Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.google_video_icon);
        iv_recievedfile.setImageBitmap(b);
    } else if (isaudioMsg(subject)) {
        text_view.setVisibility(TextView.GONE);
        iv_recievedfile.setVisibility(ImageView.VISIBLE);
        Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.google_audio_icon);
        iv_recievedfile.setImageBitmap(b);
    } else if (islocationMsg(subject)) {
        text_view.setVisibility(TextView.GONE);
        iv_recievedfile.setVisibility(ImageView.VISIBLE);
        Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.google_map_icon);
        iv_recievedfile.setImageBitmap(b);
    } else if (iscontactMsg(subject)) {
        tv_msg_info.setText("1");
        text_view.setVisibility(TextView.GONE);
        iv_recievedfile.setVisibility(ImageView.VISIBLE);
        Bitmap b = BitmapFactory.decodeResource(context.getResources(), R.drawable.google_contact_icon);
        iv_recievedfile.setImageBitmap(b);
    } else if (isimageMsg(subject)) {
        text_view.setVisibility(TextView.GONE);
        iv_recievedfile.setVisibility(ImageView.VISIBLE);
        Log.d("subject outgoingImage", subject);

        if (subject.contains("@@")) {
            String[] fileuriarr = subject.split("@@");
            String fileuri = fileuriarr[1];
            String[] namm = fileuri.split("-");
            String path = Environment.getExternalStorageDirectory() + "/R4W/SharingImage/" + stripNumber(numb)
                    + "/send/" + namm[2];
            Log.d("fileuri1", fileuri);
            Log.d("path1", path);
            File user_imageFile = new File(path);
            if (user_imageFile.exists()) {
                Bitmap b = BitmapFactory.decodeFile(path);

                int[] size = messageActivity.getBitmapSize(b);
                b = Bitmap.createScaledBitmap(b, size[0], size[1], false);
                Log.d("imageFile.exists", "true");
                Log.d("bitmap", b.getWidth() + " @");
                iv_recievedfile.setImageBitmap(b);
                /*
                 iv_recievedfile.setImageURI(Uri.parse(imageFile.getAbsolutePath()));
                 Log.d("imageFile.getAbsolutePath()", imageFile.getAbsolutePath());
                 */
            }
        }

    } else {
        text_view.setVisibility(TextView.VISIBLE);
        iv_recievedfile.setVisibility(ImageView.GONE);
        pb_uploading.setVisibility(ProgressBar.GONE);
    }
}

From source file:ca.ualberta.cmput301w14t08.geochan.fragments.PostFragment.java

/**
 * Scales a bitmap to a suitable size for display.
 * @param bitmap The Bitmap to be scaled.
 * @return The rescaled Bitmap.//from  w  ww. j  a v a  2s .co m
 * 
 */
private Bitmap scaleImage(Bitmap bitmap) {
    // https://github.com/bradleyjsimons/PicPoster/blob/master/src/ca/ualberta/cs/picposter/controller/PicPosterController.java
    // Scale the pic if it is too large:
    if (bitmap.getWidth() > MAX_BITMAP_DIMENSIONS || bitmap.getHeight() > MAX_BITMAP_DIMENSIONS) {
        double scalingFactor = bitmap.getWidth() * 1.0 / MAX_BITMAP_DIMENSIONS;
        if (bitmap.getHeight() > bitmap.getWidth())
            scalingFactor = bitmap.getHeight() * 1.0 / MAX_BITMAP_DIMENSIONS;

        int newWidth = (int) Math.round(bitmap.getWidth() / scalingFactor);
        int newHeight = (int) Math.round(bitmap.getHeight() / scalingFactor);

        bitmap = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, false);
    }
    return bitmap;
}

From source file:com.dunrite.xpaper.utility.Utils.java

public static Drawable combineImages2(Drawable background, Drawable foreground, Drawable deviceMisc,
        int backgroundCol, int foregroundCol, String type, Context context) {
    Bitmap cs;//w  ww .  j ava 2 s .  c o  m
    Bitmap device = null;
    int width;
    int height;

    //TEXTURE TESTING
    String textureLocation = "";
    Bitmap foregroundTexture = null;
    //TODO: will need some type of way to know which location to put the texture (foreground/background/both)
    //        String textureLocation = "foreground";
    //        type = "";
    //TODO: will need some type of way to know which foreground texture drawable to pull from
    //        Bitmap foregroundTexture = ((BitmapDrawable) ContextCompat.getDrawable(context, R.drawable.texture_bamboo)).getBitmap();
    //        foregroundTexture = foregroundTexture.copy(Bitmap.Config.ARGB_8888, true);

    //convert from drawable to bitmap
    Bitmap back = ((BitmapDrawable) background).getBitmap();
    back = back.copy(Bitmap.Config.ARGB_8888, true);

    Bitmap fore = ((BitmapDrawable) foreground).getBitmap();
    fore = fore.copy(Bitmap.Config.ARGB_8888, true);

    if (type.equals("device")) {
        device = ((BitmapDrawable) deviceMisc).getBitmap();
        device = device.copy(Bitmap.Config.ARGB_8888, true);
    }
    //initialize Canvas
    if (type.equals("preview") || type.equals("device")) {
        width = back.getWidth() / 2;
        height = back.getHeight() / 2;
    } else {
        width = back.getWidth();
        height = back.getHeight();
    }
    cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas comboImage = new Canvas(cs);

    Paint paint1 = new Paint();
    paint1.setFilterBitmap(false);
    //Filter for Background
    if (textureLocation.equals("background") || textureLocation.equals("both")) {
        paint1.setColorFilter(new PorterDuffColorFilter(backgroundCol, PorterDuff.Mode.DST_ATOP));
    } else {
        paint1.setColorFilter(new PorterDuffColorFilter(backgroundCol, PorterDuff.Mode.SRC_ATOP));
    }

    //Filter for Foreground
    Paint paint2 = new Paint();
    paint2.setFilterBitmap(false);
    if (textureLocation.equals("foreground") || textureLocation.equals("both")) {
        //DIFFICULT CASE
        //create new canvas to combine
        Canvas foreCanvas = new Canvas(fore);

        //set up paint for texture
        Paint paintTexture = new Paint();
        paintTexture.setFilterBitmap(false);
        paintTexture.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        //draw our combination
        foreCanvas.drawBitmap(foregroundTexture, 0, 0, paintTexture);

        //set up theme for outer image
        paint2.setColorFilter(new PorterDuffColorFilter(foregroundCol, PorterDuff.Mode.DST_IN));
    } else {
        paint2.setColorFilter(new PorterDuffColorFilter(foregroundCol, PorterDuff.Mode.SRC_ATOP));
    }

    //Draw both images
    if (type.equals("preview") || type.equals("device")) {
        if (type.equals("device") && device != null) {
            comboImage.drawBitmap(
                    Bitmap.createScaledBitmap(device, device.getWidth() / 2, device.getHeight() / 2, true), 0,
                    0, null);
            device.recycle();
        }
        comboImage.drawBitmap(Bitmap.createScaledBitmap(back, back.getWidth() / 2, back.getHeight() / 2, true),
                0, 0, paint1);
        comboImage.drawBitmap(Bitmap.createScaledBitmap(fore, fore.getWidth() / 2, fore.getHeight() / 2, true),
                0, 0, paint2);

    } else {
        comboImage.drawBitmap(back, 0, 0, paint1);
        comboImage.drawBitmap(fore, 0, 0, paint2);
    }
    back.recycle();
    fore.recycle();

    return new BitmapDrawable(context.getResources(), cs);
}