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.hp.mss.printsdksample.fragment.TabFragmentPrintLayout.java

private void createUserSelectedImageJobData() {
    Bitmap userPickedBitmap;/* www  . j  a  v a  2  s .c o m*/

    try {
        userPickedBitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), userPickedUri);
        int width = userPickedBitmap.getWidth();
        int height = userPickedBitmap.getHeight();

        // if user picked bitmap is too big, just reduce the size, so it will not chock the print plugin
        if (width * height > 5000) {
            width = width / 2;
            height = height / 2;
            userPickedBitmap = Bitmap.createScaledBitmap(userPickedBitmap, width, height, true);
        }

        DisplayMetrics mDisplayMetric = getActivity().getResources().getDisplayMetrics();
        float widthInches = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_IN, width, mDisplayMetric);
        float heightInches = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_IN, height, mDisplayMetric);

        ImageAsset imageAsset = new ImageAsset(getActivity(), userPickedBitmap,
                ImageAsset.MeasurementUnits.INCHES, widthInches, heightInches);

        PrintItem printItem4x6 = new ImagePrintItem(PrintAttributes.MediaSize.NA_INDEX_4X6, margins, scaleType,
                imageAsset);
        PrintItem printItem85x11 = new ImagePrintItem(PrintAttributes.MediaSize.NA_LETTER, margins, scaleType,
                imageAsset);
        PrintItem printItem5x7 = new ImagePrintItem(mediaSize5x7, margins, scaleType, imageAsset);

        printJobData = new PrintJobData(getActivity(), printItem4x6);
        printJobData.addPrintItem(printItem85x11);
        printJobData.addPrintItem(printItem5x7);
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.ritul.truckshare.RegisterActivity.DriverLicenseActivity.java

public void Image_Selecting_Task(Intent data) {
    try {/*from  www.  ja v  a2s . c  om*/
        Utility.uri = data.getData();
        if (Utility.uri != null) {
            // User had pick an image.
            Cursor cursor = getContentResolver().query(Utility.uri,
                    new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
            cursor.moveToFirst();
            // Link to the image
            final String imageFilePath = cursor.getString(0);

            //Assign string path to File
            Utility.Default_DIR = new File(imageFilePath);

            // Create new dir MY_IMAGES_DIR if not created and copy image into that dir and store that image path in valid_photo
            Utility.Create_MY_IMAGES_DIR();

            // Copy your image
            Utility.copyFile(Utility.Default_DIR, Utility.MY_IMG_DIR);

            // Get new image path and decode it
            Bitmap b = Utility.decodeFile(Utility.Paste_Target_Location);

            // use new copied path and use anywhere
            String valid_photo = Utility.Paste_Target_Location.toString();
            b = Bitmap.createScaledBitmap(b, 150, 150, true);

            //set your selected image in image view
            preview.setImageBitmap(b);
            cursor.close();

        } else {
            Toast toast = Toast.makeText(this, "Sorry!!! You haven't selecet any image.", Toast.LENGTH_LONG);
            toast.show();
        }
    } catch (Exception e) {
        // you get this when you will not select any single image
        Log.e("onActivityResult", "" + e);

    }
}

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

public Bitmap getBitmap(String imageUrl, CachePolicy cachePol) {
    if (imageUrl == null || imageUrl.length() < 1)
        return null;

    File file = getCacheFile(imageUrl, cachePol);

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

        try {//from w  w w.ja v  a2 s . com
            if (!cachePol.expired(System.currentTimeMillis(), file.lastModified()))
                return BitmapFactory.decodeFile(file.getAbsolutePath());
        } catch (OutOfMemoryError e) {
            return null;
        }
    }

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

    try {
        HttpClient client = new IgnorantHttpClient();

        HttpParams params = client.getParams();
        params.setParameter("http.useragent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0;)");

        HttpConnectionParams.setConnectionTimeout(params, TIMEOUT_MS);
        HttpConnectionParams.setSoTimeout(params, TIMEOUT_MS);

        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) {
                // Length is negative, perhaps content length is not set
                ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

                int chunkSize = 5000;
                byte[] chunk = new byte[chunkSize];

                for (int r = 0; r >= 0; r = stream.read(chunk, 0, chunkSize))
                    byteStream.write(chunk, 0, r);

                blob = byteStream.toByteArray();
            } else {
                // We know the length
                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 (cachePol.resizeWidth > 0 || cachePol.resizeHeight > 0) {
                Bitmap bmp = BitmapFactory.decodeByteArray(blob, 0, blob.length);
                float aspectRatio = (float) bmp.getWidth() / (float) bmp.getHeight();

                int newWidth = (cachePol.resizeWidth <= 0) ? (int) ((float) cachePol.resizeHeight * aspectRatio)
                        : cachePol.resizeWidth;
                int newHeight = (cachePol.resizeHeight <= 0)
                        ? (int) ((float) cachePol.resizeWidth / aspectRatio)
                        : cachePol.resizeHeight;

                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.getName());
        } 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, blob.length);
    } catch (Exception e) {
        if (App.getConfig().logToConsole())
            e.printStackTrace();
    }

    return bmp;
}

From source file:com.orpheusdroid.screenrecorder.RecorderService.java

private void showShareNotification() {
    Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
    Intent Shareintent = new Intent().setAction(Intent.ACTION_SEND)
            .putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(SAVEPATH))).setType("video/mp4");
    PendingIntent sharePendingIntent = PendingIntent.getActivity(this, 0,
            Intent.createChooser(Shareintent, getString(R.string.share_intent_title)),
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder shareNotification = new NotificationCompat.Builder(this)
            .setContentTitle(getString(R.string.share_intent_notification_title))
            .setContentText(getString(R.string.share_intent_notification_content))
            .setSmallIcon(R.drawable.ic_notification)
            .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false)).setAutoCancel(true)
            .setContentIntent(sharePendingIntent).addAction(android.R.drawable.ic_menu_share,
                    getString(R.string.share_intent_notification_action_text), sharePendingIntent);
    updateNotification(shareNotification.build(), Const.SCREEN_RECORDER_SHARE_NOTIFICATION_ID);
}

From source file:com.s8launch.cheil.facetracker.MultiTrackerActivity.java

@Override
public void onPictureTaken(byte[] data) {
    //  try {/*  w w  w . j a  v a 2 s  .  c o m*/
    Bitmap cameraBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
    Bitmap newImage = Bitmap.createBitmap(cameraBitmap.getWidth(), cameraBitmap.getHeight(),
            Bitmap.Config.ARGB_8888);

    Bitmap overlayBitmap = this.getBitmapFromView(mGraphicOverlay);

    Bitmap overlayScaledBitmap = Bitmap.createScaledBitmap(overlayBitmap, cameraBitmap.getWidth(),
            cameraBitmap.getHeight(), true);
    Canvas canvas = new Canvas(newImage);
    canvas.drawBitmap(cameraBitmap, 0, 0, null);
    canvas.drawBitmap(overlayScaledBitmap, 0, 0, null);

    File storagePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
    storagePath.mkdirs();
    String finalName = Long.toString(System.currentTimeMillis());
    File myImage = new File(storagePath, finalName + ".jpg");

    String photoPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + finalName + ".jpg";

    try {
        FileOutputStream fos = new FileOutputStream(myImage);
        newImage.compress(Bitmap.CompressFormat.JPEG, 80, fos);
        fos.close();
    } catch (IOException e) {
        Toast.makeText(MultiTrackerActivity.this, "Pic not saved", Toast.LENGTH_SHORT).show();
        return;
    }
    Toast.makeText(MultiTrackerActivity.this, "Pic saved in: " + photoPath, Toast.LENGTH_SHORT).show();

    newImage.recycle();
    newImage = null;
    cameraBitmap.recycle();
    cameraBitmap = null;
}

From source file:cl.iluminadoschile.pako.floatingdiv.CustomOverlayService.java

@Override
protected Notification foregroundNotification(int notificationId) {
    Notification notification;//  www  .j  a  va  2s . com

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            && activation_method.equals(Constants.SETTINGS.ACTIVATION_METHOD_MANUAL)) {
        Intent settingsIntent = new Intent(Intent.ACTION_MAIN);
        settingsIntent.setClassName(Constants.ACTION.prefix, Constants.ACTION.prefix + ".SettingsActivity");
        settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, settingsIntent, 0);

        Intent startFgIntent = new Intent(this, CustomOverlayService.class);
        startFgIntent.setAction(Constants.ACTION.STARTFOREGROUND_ACTION);
        PendingIntent pstartFgIntent = PendingIntent.getService(this, 0, startFgIntent, 0);

        Intent pauseFgIntent = new Intent(this, CustomOverlayService.class);
        pauseFgIntent.setAction(Constants.ACTION.PAUSEFOREGROUND_ACTION);
        PendingIntent ppauseFgIntent = PendingIntent.getService(this, 0, pauseFgIntent, 0);

        Intent stopFgIntent = new Intent(this, CustomOverlayService.class);
        stopFgIntent.setAction(Constants.ACTION.STOPFOREGROUND_ACTION);
        PendingIntent pstopFgIntent = PendingIntent.getService(this, 0, stopFgIntent, 0);

        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

        notification = new NotificationCompat.Builder(this)
                .setContentTitle(getString(R.string.title_notification))
                .setTicker(getString(R.string.title_notification))
                .setContentText(getString(R.string.message_notification)).setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(Bitmap.createScaledBitmap(icon, 128, 128, false)).setContentIntent(pendingIntent)
                .setOngoing(true).addAction(android.R.drawable.ic_media_play, "Start", pstartFgIntent)
                .addAction(android.R.drawable.ic_media_pause, "Pause", ppauseFgIntent)
                .addAction(android.R.drawable.ic_delete, "Stop", pstopFgIntent).build();

    } else {
        notification = new Notification(R.drawable.ic_launcher, getString(R.string.title_notification),
                System.currentTimeMillis());

        notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT
                | Notification.FLAG_ONLY_ALERT_ONCE;

        notification.setLatestEventInfo(this, getString(R.string.title_notification),
                getString(R.string.message_notification_manual), notificationIntent());
    }
    return notification;
}

From source file:com.initiativaromania.hartabanilorpublici.IRUserInterface.activities.MainActivity.java

public void displayBuyers() {

    System.out.println("Displaying the available buyers");

    /* Prepare the bitmap image */
    if (bitmapIcon == null) {
        Bitmap imageBitmap = BitmapFactory.decodeResource(getResources(),
                getResources().getIdentifier("euro", "drawable", getPackageName()));
        Bitmap resizedBitmap = Bitmap.createScaledBitmap(imageBitmap, imageBitmap.getWidth() / 4,
                imageBitmap.getHeight() / 4, false);
        bitmapIcon = BitmapDescriptorFactory.fromBitmap(resizedBitmap);
    }/* ww w.j  ava2  s .c  om*/

    /* Set a pin for each buyer */
    for (Buyer buyer : CommManager.buyers) {
        /* Add pin to the map */
        LatLng location = new LatLng(buyer.latitude, buyer.longitude);

        Marker marker = mMap.addMarker(
                new MarkerOptions().position(location).title("Autoritate contractanta").icon(bitmapIcon));

        markerBuyers.put(marker, buyer);
    }

    /* Set on click listener for each pin */
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(Marker marker) {
            Buyer buyer = markerBuyers.get(marker);

            if (buyer != null) {
                /* Start a separate view for a buyer */
                Intent intent = new Intent(getBaseContext(), ParticipantActivity.class);
                intent.putExtra(ParticipantActivity.CONTRACT_LIST_TYPE,
                        ParticipantActivity.CONTRACT_LIST_FOR_BUYER);
                intent.putExtra(ParticipantActivity.CONTRACT_LIST_EXTRA, buyer.name);
                startActivity(intent);
            } else {
                /* Offer details about the user's position */
                Toast.makeText(getBaseContext(),
                        "Asta e pozitia ta. Modifica aria de interes si vezi statistici "
                                + "despre contractele din jurul tau",
                        Toast.LENGTH_LONG).show();
            }

            return true;
        }
    });
}

From source file:com.example.util.ImageUtils.java

/**
 *  /*from   ww  w . ja  v  a 2  s.c om*/
 */
public static Bitmap sacleBitmap(Context context, Bitmap bitmap) {
    // 
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    int screenWidth = metrics.widthPixels;
    float aspectRatio = (float) screenWidth / (float) width;
    int scaledHeight = (int) (height * aspectRatio);
    Bitmap scaledBitmap = null;
    try {
        scaledBitmap = Bitmap.createScaledBitmap(bitmap, screenWidth, scaledHeight, false);
    } catch (OutOfMemoryError e) {
    }
    return scaledBitmap;
}

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

/**
 * Scales the passed bitmap down so that it does not exceed the
 * maximum dimensions specified in EditCommentFragment.MAX_BITMAP_DIMENSIONS.
 * @param bitmap The bitmap that is to be scaled down.
 * @return A new Bitmap that is a scaled down version of the passed Bitmap.
 *//*from ww w.j  a v a 2s .  c o  m*/
private Bitmap scaleImage(Bitmap bitmap) {
    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, true);
    }
    return bitmap;
}

From source file:com.mappn.gfan.common.util.ImageUtils.java

/**
 * ??? /*from   w  w  w . j a  v  a 2s.  c  o  m*/
 */
public static Bitmap sacleBitmap(Context context, Bitmap bitmap) {
    // ???
    int width = bitmap.getWidth();
    int height = bitmap.getHeight();
    DisplayMetrics metrics = context.getResources().getDisplayMetrics();
    int screenWidth = metrics.widthPixels;
    float aspectRatio = (float) screenWidth / (float) width;
    int scaledHeight = (int) (height * aspectRatio);
    Bitmap scaledBitmap = null;
    try {
        scaledBitmap = Bitmap.createScaledBitmap(bitmap, screenWidth, scaledHeight, false);
    } catch (OutOfMemoryError e) {
    }
    return scaledBitmap;
}