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.hivewallet.androidclient.wallet.AddressBookProvider.java

public static Bitmap ensureReasonableSize(@Nullable Bitmap bitmap) {
    if (bitmap == null)
        return null;

    BitmapSize newSize = GenericUtils.calculateReasonableSize(bitmap.getWidth(), bitmap.getHeight(),
            REASONABLE_BITMAP_SIZE);/*from w ww .j av  a  2s.  com*/

    return Bitmap.createScaledBitmap(bitmap, newSize.getWidth(), newSize.getHeight(), false);
}

From source file:edu.berkeley.boinc.client.NoticeNotification.java

private static final Bitmap getLargeProjectIcon(final Context context, final String projectName) {
    final Bitmap projectIconBitmap;
    try {/*from   w ww . j  av  a 2s .com*/
        return (projectIconBitmap = Monitor.getClientStatus().getProjectIconByName(projectName)) != null
                ? Bitmap.createScaledBitmap(projectIconBitmap, projectIconBitmap.getWidth() << 1,
                        projectIconBitmap.getHeight() << 1, false)
                : BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_stat_notify_boinc_normal);
    } catch (Exception e) {
        if (Log.isLoggable(Logging.TAG, Log.DEBUG)) {
            Log.d(Logging.TAG, e.getLocalizedMessage(), e);
        }
        return BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_stat_notify_boinc_normal);
    }
}

From source file:com.mahhaus.scanloto.ScannerActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_document_scan);
    //Set the flag to keep the screen on (otherwise the screen may go dark during scanning)
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    imageViewResult = (ImageView) findViewById(R.id.image_result);
    errorMessageLayout = (FrameLayout) findViewById(R.id.error_message_layout);
    errorMessage = (TextView) findViewById(R.id.textViewResult);

    documentScanView = (DocumentScanView) findViewById(R.id.document_scan_view);
    // add a camera open listener that will be called when the camera is opened or an error occurred
    //  this is optional (if not set a RuntimeException will be thrown if an error occurs)
    documentScanView.setCameraOpenListener(ScannerActivity.this);
    // the view can be configured via a json file in the assets, and this config is set here
    // (alternatively it can be configured via xml, see the Energy Example for that)
    documentScanView.setConfigFromAsset("document_view_config.json");

    // Optional: Set a ratio you want the documents to be restricted to. default is set to DIN_AX
    //documentScanView.setDocumentRatios(DocumentScanView.DocumentRatio.DIN_AX_PORTRAIT.getRatio());

    // Optional: Set a maximum deviation for the ratio. 0.15 is the default
    //documentScanView.setMaxDocumentRatioDeviation(0.15);

    // initialize Anyline with the license key and a Listener that is called if a result is found
    documentScanView.initAnyline(getString(R.string.anyline_license_key), new DocumentResultListener() {
        //            @Override
        //            public void onResult(AnylineImage transformedImage, AnylineImage fullFrame, List<PointF> documentOutline) {
        ////from   w w w  . j ava  2s  .  c o m
        //
        //            }

        @Override
        public void onResult(AnylineImage transformedImage, AnylineImage fullFrame) {
            errorMessage.setText(fullFrame.toString());
            // handle the result document images here
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            imageViewResult
                    .setImageBitmap(Bitmap.createScaledBitmap(transformedImage.getBitmap(), 100, 160, false));

            /**
             * IMPORTANT: cache provided frames here, and release them at the end of this onResult. Because
             * keeping them in memory (e.g. setting the full frame to an ImageView)
             * will result in a OutOfMemoryError soon. This error is reported in {@link #onTakePictureError
             * (Throwable)}
             *
             * Use a DiskCache http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#disk-cache
             * for example
             *
             */
            File outDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "ok");
            outDir.mkdir();
            // change the file ending to png if you want a png
            File outFile = new File(outDir, "" + System.currentTimeMillis() + ".jpg");
            try {
                // convert the transformed image into a gray scaled image internally
                // transformedImage.getGrayCvMat(false);
                // get the transformed image as bitmap
                // Bitmap bmp = transformedImage.getBitmap();
                // save the image with quality 100 (only used for jpeg, ignored for png)
                transformedImage.save(outFile, 100);
                showToast(getString(R.string.document_image_saved_to) + " " + outFile.getAbsolutePath());
            } catch (IOException e) {
                e.printStackTrace();
            }

            // release the images
            transformedImage.release();
            fullFrame.release();

        }

        @Override
        public void onPreviewProcessingSuccess(AnylineImage anylineImage) {
            // this is called after the preview of the document is completed, and a full picture will be
            // processed automatically
        }

        @Override
        public void onPreviewProcessingFailure(DocumentScanView.DocumentError documentError) {
            // this is called on any error while processing the document image
            // Note: this is called every time an error occurs in a run, so that might be quite often
            // An error message should only be presented to the user after some time

            showErrorMessageFor(documentError);
        }

        @Override
        public void onPictureProcessingFailure(DocumentScanView.DocumentError documentError) {

            showErrorMessageFor(documentError, true);
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }

            // if there is a problem, here is how images could be saved in the error case
            // this will be a full, not cropped, not transformed image
            AnylineImage image = documentScanView.getCurrentFullImage();

            if (image != null) {
                File outDir = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), "error");
                outDir.mkdir();
                File outFile = new File(outDir,
                        "" + System.currentTimeMillis() + documentError.name() + ".jpg");
                try {
                    image.save(outFile, 100);
                    Log.d(TAG, "error image saved to " + outFile.getAbsolutePath());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                image.release();
            }
        }

        @Override
        public boolean onDocumentOutlineDetected(List<PointF> list, boolean documentShapeAndBrightnessValid) {
            // is called when the outline of the document is detected. return true if the outline is consumed by
            // the implementation here, false if the outline should be drawn by the DocumentScanView
            lastOutline = list; // saving the outline for the animations
            return false;
        }

        @Override
        public void onTakePictureSuccess() {
            // this is called after the image has been captured from the camera and is about to be processed
            progressDialog = ProgressDialog.show(ScannerActivity.this, "", "", true);

            if (errorMessageAnimator != null && errorMessageAnimator.isRunning()) {
                errorMessageAnimator.cancel();
                errorMessageLayout.setVisibility(View.GONE);
            }
        }

        @Override
        public void onTakePictureError(Throwable throwable) {
            // This is called if the image could not be captured from the camera (most probably because of an
            // OutOfMemoryError)
            throw new RuntimeException(throwable);
        }

    });

    // optionally stop the scan once a valid result was returned
    // documentScanView.cancelOnResult(true);

}

From source file:com.nextgis.maplibui.util.ControlHelper.java

public static Drawable getIconByVectorType(Context context, int geometryType, int color, int defaultIcon,
        boolean syncable) {
    int drawableId;

    switch (geometryType) {
    case GTPoint:
        drawableId = R.drawable.ic_type_point;
        break;/*from w  w w. j  av a  2  s .co  m*/
    case GTMultiPoint:
        drawableId = R.drawable.ic_type_multipoint;
        break;
    case GTLineString:
        drawableId = R.drawable.ic_type_line;
        break;
    case GTMultiLineString:
        drawableId = R.drawable.ic_type_multiline;
        break;
    case GTPolygon:
        drawableId = R.drawable.ic_type_polygon;
        break;
    case GTMultiPolygon:
        drawableId = R.drawable.ic_type_multipolygon;
        break;
    default:
        return ContextCompat.getDrawable(context, defaultIcon);
    }

    BitmapDrawable icon = (BitmapDrawable) ContextCompat.getDrawable(context, drawableId);
    if (icon != null) {
        Bitmap src = icon.getBitmap();
        Bitmap bitmap = Bitmap.createBitmap(src.getWidth(), src.getHeight(), src.getConfig());
        Canvas canvas = new Canvas(bitmap);

        Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        ColorFilter filter = new PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP);
        paint.setColorFilter(filter);
        canvas.drawBitmap(src, 0, 0, paint);

        if (syncable) {
            int syncIconId = isDarkTheme(context) ? R.drawable.ic_action_refresh_dark
                    : R.drawable.ic_action_refresh_light;
            ;
            src = BitmapFactory.decodeResource(context.getResources(), syncIconId);
            src = Bitmap.createScaledBitmap(src, bitmap.getWidth() / 2, bitmap.getWidth() / 2, true);
            canvas.drawBitmap(src, bitmap.getWidth() - bitmap.getWidth() / 2,
                    bitmap.getWidth() - bitmap.getWidth() / 2, new Paint());
        }

        icon = new BitmapDrawable(context.getResources(), bitmap);
    }

    return icon;
}

From source file:com.atwal.wakeup.battery.util.Utilities.java

public static Bitmap composeIcon(Drawable icon, Drawable maskIcon, int width, int height) {
    Bitmap app_mask_icon_scaled = Bitmap.createScaledBitmap(((BitmapDrawable) maskIcon).getBitmap(), width,
            height, false);/*from  w  w w . ja va 2s .  c  o  m*/
    Bitmap icon_scaled = Bitmap.createScaledBitmap(((BitmapDrawable) icon).getBitmap(), width, height, false);
    Paint paint = new Paint();
    PorterDuffXfermode porterDuffXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    canvas.drawBitmap(app_mask_icon_scaled, 0, 0, paint);
    paint.setXfermode(porterDuffXfermode);
    canvas.drawBitmap(icon_scaled, 0, 0, paint);
    canvas.setBitmap(null);
    return bitmap;
}

From source file:org.akvo.caddisfly.sensor.colorimetry.strip.util.ResultUtil.java

public static Bitmap makeBitmap(@NonNull Mat mat) {
    try {//from  ww  w  .j av a  2  s.  c o  m
        Bitmap bitmap = Bitmap.createBitmap(mat.width(), mat.height(), Bitmap.Config.ARGB_8888);
        Utils.matToBitmap(mat, bitmap);

        //double max = bitmap.getHeight() > bitmap.getWidth() ? bitmap.getHeight() : bitmap.getWidth();
        //double min = bitmap.getHeight() < bitmap.getWidth() ? bitmap.getHeight() : bitmap.getWidth();
        //double ratio = min / max;
        //int width = (int) Math.max(600, max);
        //int height = (int) Math.round(ratio * width);

        return Bitmap.createScaledBitmap(bitmap, mat.width(), mat.height(), false);

    } catch (Exception e) {
        Timber.e(e);
    }
    return null;
}

From source file:com.personalcapital.personalperks.PerkNotificationService.java

private void createNotification(Intent intent) {
    int notificationId = intent.getIntExtra(EXTRA_NOTIFICATION_ID, 1);
    String perkId = intent.getStringExtra(Perk.PERK_ID);
    Perk perk = SessionManager.getInstance().getPerkWithPerkId(perkId);

    /*//w  w w  . j  av a2  s. c om
    ArrayList<Notification> notificationPages = new ArrayList<Notification>();
            
    int stepCount = mRecipe.recipeSteps.size();
            
    for (int i = 0; i < stepCount; ++i) {
    Recipe.RecipeStep recipeStep = mRecipe.recipeSteps.get(i);
    NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle();
    style.bigText(recipeStep.stepText);
    style.setBigContentTitle(String.format(
            getResources().getString(R.string.step_count), i + 1, stepCount));
    style.setSummaryText("");
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setStyle(style);
    notificationPages.add(builder.build());
    }
            
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            
    if (mRecipe.recipeImage != null) {
    Bitmap recipeImage = Bitmap.createScaledBitmap(
            AssetUtils.loadBitmapAsset(this, mRecipe.recipeImage),
            Constants.NOTIFICATION_IMAGE_WIDTH, Constants.NOTIFICATION_IMAGE_HEIGHT, false);
    builder.setLargeIcon(recipeImage);
    }
    builder.setContentTitle(mRecipe.titleText);
    builder.setContentText(mRecipe.summaryText);
    builder.setSmallIcon(R.mipmap.ic_notification_recipe);
            
    Notification notification = builder
        .extend(new NotificationCompat.WearableExtender()
                .addPages(notificationPages))
        .build();
    mNotificationManager.notify(Constants.NOTIFICATION_ID, notification);
    */

    ArrayList<Notification> notificationPages = new ArrayList<Notification>();

    if (perk.barCodeImage != null) {
        NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
        style.bigPicture(perk.barCodeImage);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setStyle(style);
        builder.setContentText(perk.modoCheckoutCode);
        notificationPages.add(builder.build());
    }

    //        NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle();
    //        style.bigText(recipeStep.stepText);
    //        style.setBigContentTitle(String.format(getResources().getString(R.string.step_count), i + 1, stepCount));
    //            style.setSummaryText("");
    //            NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    //            builder.setStyle(style);
    //            notificationPages.add(builder.build());

    // Build an intent for an action to view a map
    Intent mapIntent = new Intent(Intent.ACTION_VIEW);
    Uri geoUri = Uri.parse("geo:0,0?q=" + Uri.encode(perk.address));
    mapIntent.setData(geoUri);
    PendingIntent mapPendingIntent = PendingIntent.getActivity(this, 0, mapIntent, 0);

    NotificationCompat.Action mapAction = new NotificationCompat.Action.Builder(R.drawable.ic_map,
            getString(R.string.map), mapPendingIntent).build();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    if (perk.logoImage != null) {
        Bitmap recipeImage = Bitmap.createScaledBitmap(perk.logoImage, 280, 280, false);
        builder.setLargeIcon(recipeImage);
    }
    builder.setContentTitle(perk.merchantName);
    builder.setContentText(perk.description);
    builder.setSmallIcon(R.drawable.ic_launcher);

    Notification notification = builder
            .extend(new NotificationCompat.WearableExtender().addPages(notificationPages).addAction(mapAction))
            .build();
    NotificationManagerCompat.from(this).notify(notificationId, notification);
}

From source file:com.example.d062654.faciliman._2_IncidentPicture.java

private void previewCapturedImage(Intent data) {
    try {/*w  w  w  .j  ava  2 s .co  m*/

        //Bundle extras = data.getExtras();
        imgPreview.setVisibility(View.VISIBLE);
        int targetW = imgPreview.getWidth();
        int targetH = imgPreview.getHeight();
        // bimatp factory
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, options);
        int photoW = options.outWidth;
        int photoH = options.outHeight;
        int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
        options.inJustDecodeBounds = false;
        options.inSampleSize = scaleFactor;
        options.inPurgeable = true;
        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
        Matrix matrix = new Matrix();

        matrix.postRotate(90);

        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), true);

        Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap, 0, 0, scaledBitmap.getWidth(),
                scaledBitmap.getHeight(), matrix, true);
        imgPreview.setImageBitmap(rotatedBitmap);

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

From source file:com.frapim.windwatch.Notifier.java

public Bitmap createIcon(Context context, Wind wind) {
    Paint paint = new Paint();
    int color = wind.scale.getColor(context);
    paint.setColor(color);/*  w ww. ja va 2  s  .c  om*/
    paint.setStyle(Style.FILL_AND_STROKE);
    Bitmap bitmap = Bitmap.createBitmap(mBigIconSize, mBigIconSize, Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    Bitmap backgroundBmp = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.turbine);
    Bitmap backgroundScaled = Bitmap.createScaledBitmap(backgroundBmp, mBigIconSize, mBigIconSize, false);
    canvas.drawBitmap(backgroundScaled, new Matrix(), new Paint());
    canvas.drawPath(getArrowPath(wind.degrees), paint);
    return bitmap;
}

From source file:com.dalaran.LDCache.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override/*from ww w. j  a v a2s .  c  o m*/
public void putBitmap(String url, Bitmap bitmap) {

    if (bitmap.getHeight() >= 100 && bitmap.getWidth() >= 100) {

        bitmap = Bitmap.createScaledBitmap(bitmap, 100, 100, false);
    }

    Log.d("Disc cached:", url);
    final Cache.Entry entry = new Cache.Entry();

    try {
        ByteBuffer buffer = ByteBuffer.allocate(bitmap.getByteCount());
        bitmap.copyPixelsToBuffer(buffer);
        entry.data = buffer.array();
        put(url, entry);
        logicToPutBitmap(url, bitmap);
    } catch (Throwable e) {
        Log.w("Samsung 2.3.3", e.getMessage(), e);
    }
}