Java Code Examples for android.graphics.Bitmap.getConfig()

The following are Jave code examples for showing how to use getConfig() of the android.graphics.Bitmap class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: GitHub   File: Util.java   View Source Code Vote up 6 votes
/**
 * Returns the in memory size of the given {@link Bitmap} in bytes.
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public static int getBitmapByteSize(Bitmap bitmap) {
  // The return value of getAllocationByteCount silently changes for recycled bitmaps from the
  // internal buffer size to row bytes * height. To avoid random inconsistencies in caches, we
  // instead assert here.
  if (bitmap.isRecycled()) {
    throw new IllegalStateException("Cannot obtain size for recycled Bitmap: " + bitmap
        + "[" + bitmap.getWidth() + "x" + bitmap.getHeight() + "] " + bitmap.getConfig());
  }
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    // Workaround for KitKat initial release NPE in Bitmap, fixed in MR1. See issue #148.
    try {
      return bitmap.getAllocationByteCount();
    } catch (NullPointerException e) {
      // Do nothing.
    }
  }
  return bitmap.getHeight() * bitmap.getRowBytes();
}
 
Example 2
Project: Glide-transformations   File: CropSquareTransformation.java   View Source Code Vote up 6 votes
@Override
public Resource<Bitmap> transform(Resource<Bitmap> resource, int outWidth, int outHeight) {
  Bitmap source = resource.get();
  int size = Math.min(source.getWidth(), source.getHeight());

  mWidth = (source.getWidth() - size) / 2;
  mHeight = (source.getHeight() - size) / 2;

  Bitmap.Config config =
      source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888;
  Bitmap bitmap = mBitmapPool.get(mWidth, mHeight, config);
  if (bitmap == null) {
    bitmap = Bitmap.createBitmap(source, mWidth, mHeight, size, size);
  }

  return BitmapResource.obtain(bitmap, mBitmapPool);
}
 
Example 3
Project: homunculus   File: BitmapPoolFactory.java   View Source Code Vote up 6 votes
@Override
public int countBitmaps(int width, int height, Config config) {
    int c = 0;
    synchronized (mCache) {
        Iterator<Bitmap> it = mCache.iterator();
        while (it.hasNext()) {
            Bitmap bmp = it.next();
            if (bmp.isRecycled()) {
                it.remove();
                continue;
            }
            if (bmp.getWidth() == width && bmp.getHeight() == height && bmp.getConfig() == config) {
                c++;
            }
        }
    }
    return c;
}
 
Example 4
Project: GitHub   File: Downsampler.java   View Source Code Vote up 5 votes
@Nullable
@TargetApi(Build.VERSION_CODES.KITKAT)
private static String getBitmapString(Bitmap bitmap) {
  if (bitmap == null) {
    return null;
  }

  String sizeString = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
      ? " (" + bitmap.getAllocationByteCount() + ")" : "";
  return  "[" + bitmap.getWidth() + "x" + bitmap.getHeight() + "] " + bitmap.getConfig()
      + sizeString;
}
 
Example 5
Project: custode   File: CustodeUtils.java   View Source Code Vote up 5 votes
public static Bitmap getRoundedBitmap(Bitmap input, int targetWidth, int targetHeight) {
    if (input == null) {
        return null;
    }
    final Bitmap.Config inputConfig = input.getConfig();
    final Bitmap result = Bitmap.createBitmap(targetWidth, targetHeight,
            inputConfig != null ? inputConfig : Bitmap.Config.ARGB_8888);
    final Canvas canvas = new Canvas(result);
    final Paint paint = new Paint();
    canvas.drawARGB(0, 0, 0, 0);
    paint.setAntiAlias(true);
    final RectF dst = new RectF(0, 0, targetWidth, targetHeight);
    canvas.drawOval(dst, paint);

    // Specifies that only pixels present in the destination (i.e. the drawn oval) should
    // be overwritten with pixels from the input bitmap.
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

    final int inputWidth = input.getWidth();
    final int inputHeight = input.getHeight();

    // Choose the largest scale factor that will fit inside the dimensions of the
    // input bitmap.
    final float scaleBy = Math.min((float) inputWidth / targetWidth,
            (float) inputHeight / targetHeight);

    final int xCropAmountHalved = (int) (scaleBy * targetWidth / 2);
    final int yCropAmountHalved = (int) (scaleBy * targetHeight / 2);

    final Rect src = new Rect(
            inputWidth / 2 - xCropAmountHalved,
            inputHeight / 2 - yCropAmountHalved,
            inputWidth / 2 + xCropAmountHalved,
            inputHeight / 2 + yCropAmountHalved);

    canvas.drawBitmap(input, src, dst, paint);
    return result;
}
 
Example 6
Project: GitHub   File: Downsampler.java   View Source Code Vote up 5 votes
@Nullable
@TargetApi(Build.VERSION_CODES.KITKAT)
private static String getBitmapString(Bitmap bitmap) {
  if (bitmap == null) {
    return null;
  }

  String sizeString = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
      ? " (" + bitmap.getAllocationByteCount() + ")" : "";
  return  "[" + bitmap.getWidth() + "x" + bitmap.getHeight() + "] " + bitmap.getConfig()
      + sizeString;
}
 
Example 7
Project: react-native-sunmi-inner-printer   File: BitmapUtils.java   View Source Code Vote up 5 votes
public static Bitmap drawTextToBitmap(Context gContext, int gResId, String gText) {  
    	  Log.i(TAG, "drawTextToBitmap = " + gText);
		  Resources resources = gContext.getResources();  
		  float scale = resources.getDisplayMetrics().density;  
		  Bitmap bitmap =   
		     BitmapFactory.decodeResource(resources, gResId);  
		   
		  Bitmap.Config bitmapConfig =
		      bitmap.getConfig();  
		  // set default bitmap config if none   
		 if(bitmapConfig == null) {  
		    bitmapConfig = Bitmap.Config.ARGB_8888;
		  }  
		  // resource bitmaps are imutable,    
		  // so we need to convert it to mutable one   
		  bitmap = bitmap.copy(bitmapConfig, true);  
		   
		  Canvas canvas = new Canvas(bitmap);  
		  // new antialised Paint   
		  Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);  
		  // text color - #3D3D3D   
		  paint.setColor(Color.WHITE);  
		  // text size in pixels   
		  paint.setTextSize((int) (12 * scale));  
		  // text shadow   
//		  paint.setShadowLayer(1f, 0f, 1f, Color.WHITE);  
		   
		  // draw text to the Canvas center   
		  Rect bounds = new Rect();  
		  paint.getTextBounds(gText, 0, gText.length(), bounds);  
		  int x = (bitmap.getWidth() - bounds.width())/2;  
		  int y = (bitmap.getHeight())/2 + (int)scale*2;  
		   
		  canvas.drawText(gText,  x, y, paint);  
	      
		  canvas.save(Canvas.ALL_SAVE_FLAG); 
	      canvas.restore();
		   
		  return bitmap;  
	}
 
Example 8
Project: medialibrary   File: BitmapUtils.java   View Source Code Vote up 5 votes
private static Bitmap.Config getConfig(Bitmap bitmap) {
    Bitmap.Config config = bitmap.getConfig();
    if (config == null) {
        config = Bitmap.Config.ARGB_8888;
    }
    return config;
}
 
Example 9
Project: GitHub   File: BasePostprocessor.java   View Source Code Vote up 5 votes
/**
 * Copies the content of <code>sourceBitmap</code> to <code>destBitmap</code>. Both bitmaps must
 * have the same width and height. If their {@link Bitmap.Config} are identical, the memory is
 * directly copied. Otherwise, the <code>sourceBitmap</code> is drawn into
 * <code>destBitmap</code>.
 */
private static void internalCopyBitmap(Bitmap destBitmap, Bitmap sourceBitmap) {
  if (destBitmap.getConfig() == sourceBitmap.getConfig()) {
    Bitmaps.copyBitmap(destBitmap, sourceBitmap);
  } else {
    // The bitmap configurations might be different when the source bitmap's configuration is
    // null, because it uses an internal configuration and the destination bitmap's configuration
    // is the FALLBACK_BITMAP_CONFIGURATION. This is the case for static images for animated GIFs.
    Canvas canvas = new Canvas(destBitmap);
    canvas.drawBitmap(sourceBitmap, 0, 0, null);
  }
}
 
Example 10
Project: ultrasonic   File: ImageLoader.java   View Source Code Vote up 5 votes
public Bitmap getImageBitmap(String username, int size)
{
	Bitmap bitmap = cache.get(getKey(username, size));

	if (bitmap != null && !bitmap.isRecycled())
	{
		Bitmap.Config config = bitmap.getConfig();
		return bitmap.copy(config, false);
	}

	return null;
}
 
Example 11
Project: MVVMFrames   File: BlurRenderScriptHelper.java   View Source Code Vote up 5 votes
/**
 * blur a given bitmap
 *
 * @param sentBitmap       bitmap to blur
 * @param radius           blur radius
 * @param canReuseInBitmap true if bitmap must be reused without blur
 * @param context          used by RenderScript, can be null if RenderScript disabled
 * @return blurred bitmap
 */
public static Bitmap doBlur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap, Context context) {
    Bitmap bitmap;

    if (canReuseInBitmap) {
        bitmap = sentBitmap;
    } else {
        bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
    }

    if (bitmap.getConfig() == Bitmap.Config.RGB_565) {
        // RenderScript hates RGB_565 so we convert it to ARGB_8888
        // (see http://stackoverflow.com/questions/21563299/
        // defect-of-image-with-scriptintrinsicblur-from-support-library)
        bitmap = convertRGB565toARGB888(bitmap);
    }

    try {
        final RenderScript rs = RenderScript.create(context);
        final Allocation input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE,
                Allocation.USAGE_SCRIPT);
        final Allocation output = Allocation.createTyped(rs, input.getType());
        final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        script.setRadius(radius);
        script.setInput(input);
        script.forEach(output);
        output.copyTo(bitmap);
        return bitmap;
    } catch (RSRuntimeException e) {
        Log.e(TAG, "RenderScript known error : https://code.google.com/p/android/issues/detail?id=71347 "
                + "continue with the FastBlur approach.");
    }

    return null;
}
 
Example 12
Project: Hitalk   File: RenderScriptBlurHelper.java   View Source Code Vote up 5 votes
/**
 * blur a given bitmap
 *
 * @param sentBitmap       bitmap to blur
 * @param radius           blur radius
 * @param canReuseInBitmap true if bitmap must be reused without blur
 * @param context          used by RenderScript, can be null if RenderScript disabled
 * @return blurred bitmap
 */
public static Bitmap doBlur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap, Context context) {
    Bitmap bitmap;

    if (canReuseInBitmap) {
        bitmap = sentBitmap;
    } else {
        bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
    }

    if (bitmap.getConfig() == Bitmap.Config.RGB_565) {
        // RenderScript hates RGB_565 so we convert it to ARGB_8888
        // (see http://stackoverflow.com/questions/21563299/
        // defect-of-image-with-scriptintrinsicblur-from-support-library)
        bitmap = convertRGB565toARGB888(bitmap);
    }

    try {
        final RenderScript rs = RenderScript.create(context);
        final Allocation input = Allocation.createFromBitmap(rs, bitmap, Allocation.MipmapControl.MIPMAP_NONE,
            Allocation.USAGE_SCRIPT);
        final Allocation output = Allocation.createTyped(rs, input.getType());
        final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        script.setRadius(radius);
        script.setInput(input);
        script.forEach(output);
        output.copyTo(bitmap);
        return bitmap;
    } catch (RSRuntimeException e) {
        Log.e(TAG, "RenderScript known error : https://code.google.com/p/android/issues/detail?id=71347 "
            + "continue with the FastBlur approach.");
    }

    return null;
}
 
Example 13
Project: xbot_head   File: ImageUtils.java   View Source Code Vote up 5 votes
public static Bitmap cropFace(FaceResult face, Bitmap bitmap, int rotate) {
    Bitmap bmp;

    float eyesDis = face.eyesDistance();
    PointF mid = new PointF();
    face.getMidPoint(mid);

    Rect rect = new Rect(
            (int) (mid.x - eyesDis * 1.20f),
            (int) (mid.y - eyesDis * 0.55f),
            (int) (mid.x + eyesDis * 1.20f),
            (int) (mid.y + eyesDis * 1.85f));

    Bitmap.Config config = Bitmap.Config.RGB_565;
    if (bitmap.getConfig() != null) config = bitmap.getConfig();
    bmp = bitmap.copy(config, true);

    switch (rotate) {
        case 90:
            bmp = ImageUtils.rotate(bmp, 90);
            break;
        case 180:
            bmp = ImageUtils.rotate(bmp, 180);
            break;
        case 270:
            bmp = ImageUtils.rotate(bmp, 270);
            break;
    }

    bmp = ImageUtils.cropBitmap(bmp, rect);
    return bmp;
}
 
Example 14
Project: PlusGram   File: TiledBitmapCanvas.java   View Source Code Vote up 5 votes
public TiledBitmapCanvas(Bitmap bitmap, int tileSize, int maxVersions) {
    mWidth = bitmap.getWidth();
    mHeight = bitmap.getHeight();
    mConfig = bitmap.getConfig();
    mTileSize = tileSize;
    mMaxVersions = maxVersions;
    load(bitmap);
}
 
Example 15
Project: GongXianSheng   File: CommonUtils.java   View Source Code Vote up 4 votes
public static Bitmap drawTextToBitmap(Context mContext, int resourceId, String mText) {
	try {
		Resources resources = mContext.getResources();
		float scale = resources.getDisplayMetrics().density;
		Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId);

		android.graphics.Bitmap.Config bitmapConfig =   bitmap.getConfig();
		// set default bitmap config if none
		if(bitmapConfig == null) {
			bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
		}
		// resource bitmaps are imutable,
		// so we need to convert it to mutable one
		bitmap = bitmap.copy(bitmapConfig, true);

		Canvas canvas = new Canvas(bitmap);
		// new antialised Paint
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		// text color - #3D3D3D
		paint.setColor(Color.WHITE);
		// text size in pixels
		paint.setTextSize((int) (12 * scale));
		// text shadow
		paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);

		// draw text to the Canvas center
		Rect bounds = new Rect();
		paint.getTextBounds(mText, 0, mText.length(), bounds);
		int x = (bitmap.getWidth() - bounds.width())/6;
		int y = (bitmap.getHeight() - bounds.height())/3;

		canvas.drawText(mText, x * scale, y * scale, paint);

		return bitmap;
	} catch (Exception e) {
		// TODO: handle exception



		return null;
	}

}
 
Example 16
Project: GitHub   File: TransformationUtils.java   View Source Code Vote up 4 votes
private static Bitmap.Config getSafeConfig(Bitmap bitmap) {
  return bitmap.getConfig() != null ? bitmap.getConfig() : Bitmap.Config.ARGB_8888;
}
 
Example 17
Project: Hello-Music-droid   File: MusicService.java   View Source Code Vote up 4 votes
private void updateMediaSession(final String what) {
    int playState = mIsSupposedToBePlaying
            ? PlaybackStateCompat.STATE_PLAYING
            : PlaybackStateCompat.STATE_PAUSED;

    if (what.equals(PLAYSTATE_CHANGED) || what.equals(POSITION_CHANGED)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setPlaybackState(new PlaybackStateCompat.Builder()
                    .setState(playState, position(), 1.0f)
                    .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE |
                            PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
                    .build());
        }
    } else if (what.equals(META_CHANGED) || what.equals(QUEUE_CHANGED)) {
        Bitmap albumArt = null;
        if (mShowAlbumArtOnLockscreen) {
            albumArt = ImageLoader.getInstance().loadImageSync(TimberUtils.getAlbumArtUri(getAlbumId()).toString());
            if (albumArt != null) {

                Bitmap.Config config = albumArt.getConfig();
                if (config == null) {
                    config = Bitmap.Config.ARGB_8888;
                }
                albumArt = albumArt.copy(config, false);
            }
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mSession.setMetadata(new MediaMetadataCompat.Builder()
                    .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, getArtistName())
                    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM_ARTIST, getAlbumArtistName())
                    .putString(MediaMetadataCompat.METADATA_KEY_ALBUM, getAlbumName())
                    .putString(MediaMetadataCompat.METADATA_KEY_TITLE, getTrackName())
                    .putLong(MediaMetadataCompat.METADATA_KEY_DURATION, duration())
                    .putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, getQueuePosition() + 1)
                    .putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, getQueue().length)
                    .putString(MediaMetadataCompat.METADATA_KEY_GENRE, getGenreName())
                    .putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, albumArt)
                    .build());

            mSession.setPlaybackState(new PlaybackStateCompat.Builder()
                    .setState(playState, position(), 1.0f)
                    .setActions(PlaybackStateCompat.ACTION_PLAY | PlaybackStateCompat.ACTION_PAUSE | PlaybackStateCompat.ACTION_PLAY_PAUSE |
                            PlaybackStateCompat.ACTION_SKIP_TO_NEXT | PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
                    .build());
        }
    }
}
 
Example 18
Project: react-native-sunmi-inner-printer   File: BitmapUtils.java   View Source Code Vote up 4 votes
/**
 * Decodes bitmap (maybe immutable) that keeps aspect-ratio and spans most within the bounds.
 */
public Bitmap decodeBitmap(byte[] data, int width, int height){
	Log.i(TAG, "width = " + width + " , " + "height = " + height);
    Bitmap bitmap = null;
    try {
        // TODO: Take max pixels allowed into account for calculation to avoid possible OOM.
        Rect bounds = getBitmapBounds(data);
        int sampleSize = Math.max(bounds.width() / width, bounds.height() / height);
        sampleSize = Math.min(sampleSize,
                Math.max(bounds.width() / height, bounds.height() / width));

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = Math.max(sampleSize, 1);
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;

        Log.i(TAG, "sampleSize = " + sampleSize + " , " + "options.inSampleSize = " + options.inSampleSize);
        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);//!!!!溢出
    } catch (Exception e) {
        Log.e(TAG,   e.getMessage());
    } finally {
    	data = null;
    }

    // Ensure bitmap in 8888 format, good for editing as well as GL compatible.
    if ((bitmap != null) && (bitmap.getConfig() != Bitmap.Config.ARGB_8888)) {
        Bitmap copy = bitmap.copy(Bitmap.Config.ARGB_8888, true);
        bitmap.recycle();
        bitmap = copy;
    }

    if (bitmap != null) {
        // Scale down the sampled bitmap if it's still larger than the desired dimension.
        float scale = Math.min((float) width / bitmap.getWidth(),
                (float) height / bitmap.getHeight());
        scale = Math.max(scale, Math.min((float) height / bitmap.getWidth(),
                (float) width / bitmap.getHeight()));
        if (scale < 1) {
            Matrix m = new Matrix();
            m.setScale(scale, scale);
            Bitmap transformed = createBitmap(
                    bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m);
            bitmap.recycle();
            return transformed;
        }
    }
    return bitmap;
}
 
Example 19
Project: SimpleUILauncher   File: HolographicOutlineHelper.java   View Source Code Vote up 4 votes
public void applyExpensiveOutlineWithBlur(Bitmap srcDst, Canvas srcDstCanvas,
        boolean clipAlpha) {
    if (ProviderConfig.IS_DOGFOOD_BUILD && srcDst.getConfig() != Bitmap.Config.ALPHA_8) {
        throw new RuntimeException("Outline blue is only supported on alpha bitmaps");
    }

    // We start by removing most of the alpha channel so as to ignore shadows, and
    // other types of partial transparency when defining the shape of the object
    if (clipAlpha) {
        byte[] pixels = new byte[srcDst.getWidth() * srcDst.getHeight()];
        ByteBuffer buffer = ByteBuffer.wrap(pixels);
        buffer.rewind();
        srcDst.copyPixelsToBuffer(buffer);

        for (int i = 0; i < pixels.length; i++) {
            if ((pixels[i] & 0xFF) < 188) {
                pixels[i] = 0;
            }
        }

        buffer.rewind();
        srcDst.copyPixelsFromBuffer(buffer);
    }

    // calculate the outer blur first
    mBlurPaint.setMaskFilter(mMediumOuterBlurMaskFilter);
    int[] outerBlurOffset = new int[2];
    Bitmap thickOuterBlur = srcDst.extractAlpha(mBlurPaint, outerBlurOffset);

    mBlurPaint.setMaskFilter(mThinOuterBlurMaskFilter);
    int[] brightOutlineOffset = new int[2];
    Bitmap brightOutline = srcDst.extractAlpha(mBlurPaint, brightOutlineOffset);

    // calculate the inner blur
    srcDstCanvas.setBitmap(srcDst);
    srcDstCanvas.drawColor(0xFF000000, PorterDuff.Mode.SRC_OUT);
    mBlurPaint.setMaskFilter(mMediumInnerBlurMaskFilter);
    int[] thickInnerBlurOffset = new int[2];
    Bitmap thickInnerBlur = srcDst.extractAlpha(mBlurPaint, thickInnerBlurOffset);

    // mask out the inner blur
    srcDstCanvas.setBitmap(thickInnerBlur);
    srcDstCanvas.drawBitmap(srcDst, -thickInnerBlurOffset[0],
            -thickInnerBlurOffset[1], mErasePaint);
    srcDstCanvas.drawRect(0, 0, -thickInnerBlurOffset[0], thickInnerBlur.getHeight(),
            mErasePaint);
    srcDstCanvas.drawRect(0, 0, thickInnerBlur.getWidth(), -thickInnerBlurOffset[1],
            mErasePaint);

    // draw the inner and outer blur
    srcDstCanvas.setBitmap(srcDst);
    srcDstCanvas.drawColor(0, PorterDuff.Mode.CLEAR);
    srcDstCanvas.drawBitmap(thickInnerBlur, thickInnerBlurOffset[0], thickInnerBlurOffset[1],
            mDrawPaint);
    srcDstCanvas.drawBitmap(thickOuterBlur, outerBlurOffset[0], outerBlurOffset[1],
            mDrawPaint);

    // draw the bright outline
    srcDstCanvas.drawBitmap(brightOutline, brightOutlineOffset[0], brightOutlineOffset[1],
            mDrawPaint);

    // cleanup
    srcDstCanvas.setBitmap(null);
    brightOutline.recycle();
    thickOuterBlur.recycle();
    thickInnerBlur.recycle();
}
 
Example 20
Project: fast_face_android   File: MainActivity.java   View Source Code Vote up 4 votes
@DebugLog
protected BitmapDrawable drawRect(String path, List<VisionDetRet> results, int color) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;
    Bitmap bm = BitmapFactory.decodeFile(path, options);
    android.graphics.Bitmap.Config bitmapConfig = bm.getConfig();
    // set default bitmap config if none
    if (bitmapConfig == null) {
        bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
    }
    // resource bitmaps are imutable,
    // so we need to convert it to mutable one
    bm = bm.copy(bitmapConfig, true);
    int width = bm.getWidth();
    int height = bm.getHeight();
    // By ratio scale
    float aspectRatio = bm.getWidth() / (float) bm.getHeight();

    final int MAX_SIZE = 512;
    int newWidth = MAX_SIZE;
    int newHeight = MAX_SIZE;
    float resizeRatio = 1;
    newHeight = Math.round(newWidth / aspectRatio);
    if (bm.getWidth() > MAX_SIZE && bm.getHeight() > MAX_SIZE) {
        Timber.tag(TAG).d("Resize Bitmap");
        bm = getResizedBitmap(bm, newWidth, newHeight);
        resizeRatio = (float) bm.getWidth() / (float) width;
        Timber.tag(TAG).d("resizeRatio " + resizeRatio);
    }

    // Create canvas to draw
    Canvas canvas = new Canvas(bm);
    Paint paint = new Paint();
    paint.setColor(color);
    paint.setStrokeWidth(2);
    paint.setStyle(Paint.Style.STROKE);
    // Loop result list
    for (VisionDetRet ret : results) {
        Rect bounds = new Rect();
        bounds.left = (int) (ret.getLeft() * resizeRatio);
        bounds.top = (int) (ret.getTop() * resizeRatio);
        bounds.right = (int) (ret.getRight() * resizeRatio);
        bounds.bottom = (int) (ret.getBottom() * resizeRatio);
        canvas.drawRect(bounds, paint);
        // Get landmark
        ArrayList<Point> landmarks = ret.getFaceLandmarks();
        for (Point point : landmarks) {
            int pointX = (int) (point.x * resizeRatio);
            int pointY = (int) (point.y * resizeRatio);
            canvas.drawCircle(pointX, pointY, 2, paint);
        }
    }

    return new BitmapDrawable(getResources(), bm);
}