Example usage for android.graphics Bitmap copy

List of usage examples for android.graphics Bitmap copy

Introduction

In this page you can find the example usage for android.graphics Bitmap copy.

Prototype

public Bitmap copy(Config config, boolean isMutable) 

Source Link

Document

Tries to make a new bitmap based on the dimensions of this bitmap, setting the new bitmap's config to the one specified, and then copying this bitmap's pixels into the new bitmap.

Usage

From source file:pl.mg6.newmaps.demo.MarkersExampleActivity.java

private Bitmap prepareBitmap() {
    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.arrow_left);
    bitmap = bitmap.copy(Config.ARGB_8888, true);
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint();
    paint.setAntiAlias(true);/* w  w  w.j a v a  2 s  .  c  om*/
    paint.setColor(Color.WHITE);
    paint.setTextAlign(Align.CENTER);
    paint.setTextSize(getResources().getDimension(R.dimen.text_size));
    String text = "mg6";
    Rect bounds = new Rect();
    paint.getTextBounds(text, 0, text.length(), bounds);
    float x = bitmap.getWidth() / 2.0f;
    float y = (bitmap.getHeight() - bounds.height()) / 2.0f - bounds.top;
    canvas.drawText(text, x, y, paint);
    return bitmap;
}

From source file:java_lang_programming.com.android_media_demo.article80.ImageFragment.java

/**
 * ??bitmap?/* ww w  .j  av a  2s .co  m*/
 * Returns changeable bmp
 *
 * @return
 */
private Bitmap getMutableBitmap() {
    BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
    Bitmap bitmap = drawable.getBitmap();

    // ??bitmap
    Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
    return mutableBitmap;
}

From source file:jahirfiquitiva.iconshowcase.tasks.WallpaperToCrop.java

private Uri getImageUri(Context inContext, Bitmap inImage) {

    Preferences mPrefs = new Preferences(inContext);
    File downloadsFolder;//ww  w  .  ja va2s .  c om

    if (inImage.isRecycled()) {
        inImage = inImage.copy(Bitmap.Config.ARGB_8888, false);
    }

    if (mPrefs.getDownloadsFolder() != null) {
        downloadsFolder = new File(mPrefs.getDownloadsFolder());
    } else {
        downloadsFolder = new File(context.getString(R.string.walls_save_location,
                Environment.getExternalStorageDirectory().getAbsolutePath()));
    }

    //noinspection ResultOfMethodCallIgnored
    downloadsFolder.mkdirs();

    File destFile = new File(downloadsFolder, wallName + ".png");

    if (!destFile.exists()) {
        try {
            inImage.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(destFile));
        } catch (final Exception e) {
            if (ShowcaseActivity.DEBUGGING)
                Utils.showLog(context, e.getLocalizedMessage());
        }
    }

    return Uri.fromFile(destFile);
}

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

/**
 * remove bitmap white around white section by miao
 *///from w ww  .  jav a  2s.c om
public static Bitmap removeAroundWhiteSection(Bitmap icon) {
    int xStart = 0;
    int xEnd = 0;
    int yStart = 0;
    int yEnd = 0;
    int width = icon.getWidth();
    int height = icon.getHeight();
    Bitmap copyIcon = icon.copy(Bitmap.Config.ARGB_8888, false);
    copyIcon = Bitmap.createScaledBitmap(copyIcon, width, 1, false);
    for (int i = 0; i < width; i++) {
        int rgb = copyIcon.getPixel(i, 0);
        if (rgb != 0 && xStart == 0) {
            xStart = i;
            continue;
        }
        if (rgb == 0 && xStart != 0) {
            xEnd = i;
        }
    }

    copyIcon = icon.copy(Bitmap.Config.ARGB_8888, false);
    copyIcon = Bitmap.createScaledBitmap(copyIcon, 1, height, false);
    for (int i = 0; i < height; i++) {
        int rgb = copyIcon.getPixel(0, i);
        if (rgb != 0 && yStart == 0) {
            yStart = i;
            continue;
        }
        if (rgb == 0 && yStart != 0) {
            yEnd = i;
        }
    }
    if (xStart < xEnd && yStart < yEnd) {
        icon = Bitmap.createBitmap(icon, xStart, yStart, xEnd - xStart, yEnd - yStart);
        Log.d(TAG, "success remove white section");
    } else {
        Log.d(TAG, "fail remove white section");
    }
    return icon;
}

From source file:com.example.android.apis.graphics.FingerPaint.java

private Bitmap loadBitmap() {
    SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
    String previouslyEncodedImage = shre.getString("paint_image_data", "");

    if (!previouslyEncodedImage.equalsIgnoreCase("")) {
        byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
        Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
        Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        return mutableBitmap;
    }//from   w  ww.jav  a2 s .com

    Display display = getWindowManager().getDefaultDisplay();
    @SuppressWarnings("deprecation")
    int width = display.getWidth();

    @SuppressWarnings("deprecation")
    int height = display.getHeight();

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    return bitmap;
}

From source file:com.silentcircle.contacts.ContactPhotoManager.java

/**
 * If necessary, decodes bytes stored in the holder to Bitmap.  As long as the
 * bitmap is held either by {@link #mBitmapCache} or by a soft reference in
 * the holder, it will not be necessary to decode the bitmap.
 *///from www .  jav  a2  s.c o  m
private static void inflateBitmap(BitmapHolder holder, int requestedExtent) {
    final int sampleSize = BitmapUtil.findOptimalSampleSize(holder.originalSmallerExtent, requestedExtent);
    byte[] bytes = holder.bytes;
    if (bytes == null || bytes.length == 0) {
        return;
    }

    if (sampleSize == holder.decodedSampleSize) {
        // Check the soft reference.  If will be retained if the bitmap is also
        // in the LRU cache, so we don't need to check the LRU cache explicitly.
        if (holder.bitmapRef != null) {
            holder.bitmap = holder.bitmapRef.get();
            if (holder.bitmap != null) {
                return;
            }
        }
    }

    try {
        Bitmap bitmap = BitmapUtil.decodeBitmapFromBytes(bytes, sampleSize);

        // make bitmap mutable and draw size onto it
        if (DEBUG_SIZES) {
            Bitmap original = bitmap;
            bitmap = bitmap.copy(bitmap.getConfig(), true);
            original.recycle();
            Canvas canvas = new Canvas(bitmap);
            Paint paint = new Paint();
            paint.setTextSize(16);
            paint.setColor(Color.BLUE);
            paint.setStyle(Style.FILL);
            canvas.drawRect(0.0f, 0.0f, 50.0f, 20.0f, paint);
            paint.setColor(Color.WHITE);
            paint.setAntiAlias(true);
            canvas.drawText(bitmap.getWidth() + "/" + sampleSize, 0, 15, paint);
        }

        holder.decodedSampleSize = sampleSize;
        holder.bitmap = bitmap;
        holder.bitmapRef = new SoftReference<Bitmap>(bitmap);
        if (DEBUG) {
            int bCount = (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB_MR1)
                    ? bitmap.getRowBytes() * bitmap.getHeight()
                    : bitmap.getByteCount();
            Log.d(TAG, "inflateBitmap " + btk(bytes.length) + " -> " + bitmap.getWidth() + "x"
                    + bitmap.getHeight() + ", " + btk(bCount));
        }
    } catch (OutOfMemoryError e) {
        // Do nothing - the photo will appear to be missing
    }
}

From source file:Main.java

/**
 * Crop image bitmap from given bitmap using the given points in the original bitmap and the given rotation.<br>
 * if the rotation is not 0,90,180 or 270 degrees then we must first crop a larger area of the image that
 * contains the requires rectangle, rotate and then crop again a sub rectangle.
 *
 * @param scale how much to scale the cropped image part, use 0.5 to lower the image by half (OOM handling)
 *///from  w  ww.  j  a v a  2  s  .  c om
private static Bitmap cropBitmapObjectWithScale(Bitmap bitmap, float[] points, int degreesRotated,
        boolean fixAspectRatio, int aspectRatioX, int aspectRatioY, float scale, boolean flipHorizontally,
        boolean flipVertically) {

    // get the rectangle in original image that contains the required cropped area (larger for non rectangular crop)
    Rect rect = getRectFromPoints(points, bitmap.getWidth(), bitmap.getHeight(), fixAspectRatio, aspectRatioX,
            aspectRatioY);

    if (degreesRotated == 90 || degreesRotated == 270) {
        if (flipHorizontally != flipVertically) {
            boolean temp = flipHorizontally;
            flipHorizontally = flipVertically;
            flipVertically = temp;
        }
    }

    // crop and rotate the cropped image in one operation
    float scaleX = flipHorizontally ? -scale : scale;
    float scaleY = flipVertically ? -scale : scale;

    Matrix matrix = new Matrix();
    matrix.setScale(scaleX, scaleY);
    matrix.postRotate(degreesRotated, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
    Bitmap result = Bitmap.createBitmap(bitmap, rect.left, rect.top, rect.width(), rect.height(), matrix, true);

    if (result == bitmap) {
        // corner case when all bitmap is selected, no worth optimizing for it
        result = bitmap.copy(bitmap.getConfig(), false);
    }

    // rotating by 0, 90, 180 or 270 degrees doesn't require extra cropping
    if (degreesRotated % 90 != 0) {

        // extra crop because non rectangular crop cannot be done directly on the image without rotating first
        result = cropForRotatedImage(result, points, rect, degreesRotated, fixAspectRatio, aspectRatioX,
                aspectRatioY);
    }

    return result;
}

From source file:com.dongbang.yutian.activity.CommonScanActivity.java

/**
 *
 *//*from   ww w.  ja  va 2 s.  co  m*/
public void scanResult(Result rawResult, Bundle bundle) {
    //????????????reScan()
    //scanManager.reScan();
    //      Toast.makeText(that, "result="+rawResult.getText(), Toast.LENGTH_LONG).show();

    if (!scanManager.isScanning()) { //?????
        //???
        rescan.setVisibility(View.VISIBLE);
        scan_image.setVisibility(View.VISIBLE);
        Bitmap barcode = null;
        byte[] compressedBitmap = bundle.getByteArray(DecodeThread.BARCODE_BITMAP);
        if (compressedBitmap != null) {
            barcode = BitmapFactory.decodeByteArray(compressedBitmap, 0, compressedBitmap.length, null);
            barcode = barcode.copy(Bitmap.Config.ARGB_8888, true);
        }
        scan_image.setImageBitmap(barcode);
    }
    rescan.setVisibility(View.VISIBLE);
    scan_image.setVisibility(View.VISIBLE);
    tv_scan_result.setVisibility(View.VISIBLE);
    tv_scan_result.setText("" + rawResult.getText());
    //        Toast.makeText(this,""+rawResult.getText(),Toast.LENGTH_SHORT).show();
    //      result=rawResult.getText();
    ScanResult.setResult(rawResult.getText());
    finish();
    Intent it = new Intent(this, ProductInfoActivity.class);
    startActivity(it);
}

From source file:com.liwn.zzl.markbit.DrawOptionsMenuActivity.java

protected void initialiseWithMarkPath(String markPath) {
    //        File file = FileIO.getFileByPath(markPath);
    File file = new File(markPath);

    if (file != null) {
        Bitmap bitmap = BitmapFactory.decodeFile(markPath);
        initialiseWithBitmap(bitmap.copy(Config.ARGB_8888, true));
    } else {//from  w w w.  jav  a 2 s.com
        Log.e("Initialise by Mark ID: ", "faild for file is null");
        initialiseNewBitmap();
    }
}

From source file:com.android.messaging.datamodel.BugleNotifications.java

private static void sendNotification(final NotificationState notificationState, final Bitmap avatarIcon,
        final Bitmap avatarHiRes) {
    final Context context = Factory.get().getApplicationContext();
    if (notificationState.mCanceled) {
        if (LogUtil.isLoggable(TAG, LogUtil.DEBUG)) {
            LogUtil.d(TAG, "sendNotification: Notification already cancelled; dropping it");
        }//ww w.j av a  2s .co  m
        return;
    }

    synchronized (sPendingNotifications) {
        if (sPendingNotifications.contains(notificationState)) {
            sPendingNotifications.remove(notificationState);
        }
    }

    notificationState.mNotificationBuilder.setSmallIcon(notificationState.getIcon())
            .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
            .setColor(context.getResources().getColor(R.color.notification_accent_color))
            //            .setPublicVersion(null)    // TODO: when/if we ever support different
            // text on the lockscreen, instead of "contents hidden"
            .setCategory(CATEGORY_MESSAGE);

    if (avatarIcon != null) {
        notificationState.mNotificationBuilder.setLargeIcon(avatarIcon);
    }

    if (notificationState.mParticipantContactUris != null
            && notificationState.mParticipantContactUris.size() > 0) {
        for (final Uri contactUri : notificationState.mParticipantContactUris) {
            notificationState.mNotificationBuilder.addPerson(contactUri.toString());
        }
    }

    final Uri attachmentUri = notificationState.getAttachmentUri();
    final String attachmentType = notificationState.getAttachmentType();
    Bitmap attachmentBitmap = null;

    // For messages with photo/video attachment, request an image to show in the notification.
    if (attachmentUri != null && notificationState.mNotificationStyle != null
            && (notificationState.mNotificationStyle instanceof NotificationCompat.BigPictureStyle)
            && (ContentType.isImageType(attachmentType) || ContentType.isVideoType(attachmentType))) {
        final boolean isVideo = ContentType.isVideoType(attachmentType);

        MediaRequest<ImageResource> imageRequest;
        if (isVideo) {
            Assert.isTrue(VideoThumbnailRequest.shouldShowIncomingVideoThumbnails());
            final MessagePartVideoThumbnailRequestDescriptor videoDescriptor = new MessagePartVideoThumbnailRequestDescriptor(
                    attachmentUri);
            imageRequest = videoDescriptor.buildSyncMediaRequest(context);
        } else {
            final UriImageRequestDescriptor imageDescriptor = new UriImageRequestDescriptor(attachmentUri,
                    sWearableImageWidth, sWearableImageHeight, false /* allowCompression */,
                    true /* isStatic */, false /* cropToCircle */,
                    ImageUtils.DEFAULT_CIRCLE_BACKGROUND_COLOR /* circleBackgroundColor */,
                    ImageUtils.DEFAULT_CIRCLE_STROKE_COLOR /* circleStrokeColor */);
            imageRequest = imageDescriptor.buildSyncMediaRequest(context);
        }
        final ImageResource imageResource = MediaResourceManager.get().requestMediaResourceSync(imageRequest);
        if (imageResource != null) {
            try {
                // Copy the bitmap, because the one in the ImageResource is managed by
                // MediaResourceManager.
                Bitmap imageResourceBitmap = imageResource.getBitmap();
                Config config = imageResourceBitmap.getConfig();

                // Make sure our bitmap has a valid format.
                if (config == null) {
                    config = Bitmap.Config.ARGB_8888;
                }
                attachmentBitmap = imageResourceBitmap.copy(config, true);
            } finally {
                imageResource.release();
            }
        }
    }

    fireOffNotification(notificationState, attachmentBitmap, avatarIcon, avatarHiRes);
}