I have a bitmap:
Bitmap bitmap = BitmapFactory.decodeFile("some/arbitrary/path/image.jpg");
But I'm not going to display the image to the user. I want the alpha to be 100 (out of 255). If this is not possible, can I set the opacity of the Bitmap?
As far as I know, opacity or other color filters can't be set on the Bitmap itself. You will need to set the alpha when you use the image:
If you're using ImageView, there is ImageView.setAlpha().
If you're using a Canvas, then you need to use Paint.setAlpha():
Paint paint = new Paint();
paint.setAlpha(100);
canvas.drawBitmap(bitmap, src, dst, paint);
Also, incorporating WarrenFaith's answer, if you will use the Bitmap where a drawable is required, you can use BitmapDrawable.setAlpha().
You could also try BitmapDrawable instead of Bitmap. If this is useful for you depends on the way you use the bitmap...
Edit
As a commenter asked how he can store the bitmap with alpha, here is some code:
// lets create a new empty bitmap
Bitmap newBitmap = Bitmap.createBitmap(originalBitmap.getWidth(), originalBitmap.getHeight(), Bitmap.Config.ARGB_8888);
// create a canvas where we can draw on
Canvas canvas = new Canvas(newBitmap);
// create a paint instance with alpha
Paint alphaPaint = new Paint();
alphaPaint.setAlpha(42);
// now lets draw using alphaPaint instance
canvas.drawBitmap(originalBitmap, 0, 0, alphaPaint);
// now lets store the bitmap to a file - the canvas has drawn on the newBitmap, so we can just store that one
// please add stream handling with try/catch blocks
FileOutputStream fos = new FileOutputStream(new File("/awesome/path/to/bitmap.png"));
newBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
public Bitmap makeTransparent(Bitmap src, int value) {
int width = src.getWidth();
int height = src.getHeight();
Bitmap transBitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(transBitmap);
canvas.drawARGB(0, 0, 0, 0);
// config paint
final Paint paint = new Paint();
paint.setAlpha(value);
canvas.drawBitmap(src, 0, 0, paint);
return transBitmap;
}
Bitmap bgr = BitmapFactory.decodeResource(getResources(),R.drawable.main_logo_2);
Paint transparentpainthack = new Paint();
transparentpainthack.setAlpha(100);
canvas.drawBitmap(bgr, 0, 0, transparentpainthack);
https://dzone.com/articles/adjusting-opacity-android proposes:
/**
* #param bitmap The source bitmap.
* #param opacity a value between 0 (completely transparent) and 255 (completely
* opaque).
* #return The opacity-adjusted bitmap. If the source bitmap is mutable it will be
* adjusted and returned, otherwise a new bitmap is created.
*/
private Bitmap adjustOpacity(Bitmap bitmap, int opacity)
{
Bitmap mutableBitmap = bitmap.isMutable()
? bitmap
: bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(mutableBitmap);
int colour = (opacity & 0xFF) << 24;
canvas.drawColor(colour, PorterDuff.Mode.DST_IN);
return mutableBitmap;
}
Note that with DST_IN you can modify (rather than reset) the transparency of already transparent image, that is, you can make the image more and more transparent.
If you are using a Drawable to display the image, you can change the alpha as follows:
private Drawable mTriangle;
mTriangle = context.getResources().getDrawable(R.drawable.triangle_arrow_for_radar);
...
protected void onDraw(Canvas canvas)
{
// Draw the triangle arrow
float imageTargetWidth = getWidth() / 15;
float scale = mTriangle.getIntrinsicWidth() / imageTargetWidth;
int imgWidth = (int)(imageTargetWidth);
int imgHeight = (int)(mTriangle.getIntrinsicHeight() / scale);
if (mTriangle != null)
{
mTriangle.setBounds(getWidth() / 2 - imgWidth / 2, getHeight() / 2 - imgHeight / 2, getWidth() / 2 + imgWidth / 2, getHeight() / 2 + imgHeight / 2);
mTriangle.setAlpha(150); // from (transparent) to 255 (opaque)
mTriangle.draw(canvas);
}
}
Related
I want to add a string on bitmap image.I have a metod drawTextToBitmap,this method working success place string on bitmap image.But my bitmap image is very small like pinmark image.This function set the string based on the bitmap height and width.I want to place the string exceed than the bitmap image.So Please help me to solve the problem.
Following method i am using to get bitmap :
public Bitmap drawTextToBitmap(Context gContext, int gResId, String gText) {
Resources resources = gContext.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, gResId);
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.BLACK);
// text size in pixels
paint.setTextSize((int) (70 * scale));
// text shadow
paint.setShadowLayer(1f, 0f, 1f, Color.BLACK);
// draw text to the Canvas center
Rect bounds = new Rect();
paint.getTextBounds(gText, 0, gText.length(), bounds);
int m = (bitmap.getWidth() - bounds.width()) / 2;
int l = (bitmap.getHeight() + bounds.height()) / 2;
canvas.drawText(gText, 1000, l, paint);
return bitmap;
}
Try this:
public static Bitmap drawStringonBitmap(Bitmap src, String string, Point location, int color, int alpha, int size, boolean underline,int width ,int height) {
Bitmap result = Bitmap.createBitmap(width, height, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
paint.setColor(color);
paint.setAlpha(alpha);
paint.setTextSize(size);
paint.setAntiAlias(true);
paint.setUnderlineText(underline);
canvas.drawText(string, location.x, location.y, paint);
return result;
}
How can i cut a circle from a different shapes of bitmap in android.
I tried this code, but some images are stretched:
public Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
int targetWidth = 240;
int targetHeight = 200;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth),
((float) targetHeight)) / 2),
Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
canvas.drawBitmap(sourceBitmap,new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), null);
return targetBitmap;
}
If you want a circular cut of an image, you need to find the largest square that centers the image. Considering this, following line fixes your stretching problem:
Bitmap bitmap = ThumbnailUtils.extractThumbnail(bitmap, radius, radius, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
This method creates a circular cut of the target bitmap:
private Bitmap getCircularBitmap(int radius, Bitmap bitmap) {
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(radius, radius, conf);
Canvas canvas = new Canvas(bmp);
// creates a centered bitmap of the desired size
bitmap = ThumbnailUtils.extractThumbnail(bitmap, radius, radius, ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(shader);
RectF rect = new RectF(0, 0, radius, radius);
canvas.drawRoundRect(rect, radius, radius, paint);
return bmp;
}
One approach would be to use a BitmapShader.
The idea is to use a Paint with a BitmapShader to draw a texture using the bitmap. Then you just draw a circle on the canvas.
Here is an excellent example of using the BitmapShader. In this example, a rectangle with rounded corners is drawn, but it could just as easily be a circle.
Android Recipe #1, image with rounded corners
I've got a drawable I'm applying a filter to using
drawable.setColorFilter (color, PorterDuff.MILTIPLY)
Then I'm taking the bitmap I used to create the drawable and putting it into a canvas so I can write text in the middle of the png. And finishing by writing
drawable.draw(canvas)
I want the text I add to always be white no matter what color filter is used but right now the text becomes whatever color is used for filtering. I was thinking if I could convert the filtered drawable to a bitmap then add the text the it'd work but so far it hasnt. Any help or suggestions would be greatly appreciated.
Here is my code
public void setDrawableFilter(String text, int color) {
mBitmap = scaleBitmap(250, 238);
mDrawable = new BitmapDrawable(mContext.getResources(), mBitmap);
mDrawable.setColorFilter(color, PorterDuff.Mode.MULTIPLY);
addTextToBitmap(text);
}
public void addTextToBitmap(String text){
Canvas canvas = new Canvas(mBitmap);
mDrawable.draw(canvas);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setTextSize(35);
paint.setColor(Color.WHITE);
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
float xPercent = 0.38f;
float yPercent = 0.58f;
int textX = (int) (canvasWidth * xPercent);//
int textY = (int) (canvasHeight * yPercent);
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(text, canvasWidth / 2, textY, paint);
}
I have a bitmap and I want to create a new bitmap obtained by the first rotated around its center. Actually I use this code but it does not work.
Bitmap source = ((BitmapDrawable)r.getDrawable(R.drawable.rectangle)).getBitmap();
int targetWidth = (int)(mWidth * Math.sin(rotationAngle) + mHeight * Math.cos(rotationAngle));
int targetHeight = (int)(mWidth * Math.cos(rotationAngle) + mHeight * Math.sin(rotationAngle));
Bitmap target = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(target);
Matrix m = new Matrix();
m.setRotate(rotationAngle, targetWidth/2f, targetHeight/2f);
c.drawBitmap(source, m, null);
I also tried this code but it doesn't help.
Bitmap source = ((BitmapDrawable)r.getDrawable(R.drawable.rectangle)).getBitmap();
int targetWidth = (int)(mWidth * Math.sin(rotationAngle) + mHeight * Math.cos(rotationAngle));
int targetHeight = (int)(mWidth * Math.cos(rotationAngle) + mHeight * Math.sin(rotationAngle));
Bitmap target = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(target);
c.rotate(rotationAngle, targetWidth/2f, targetHeight/2f);
c.drawBitmap(temp, 0, 0, null);
In this case the rotate command(but the same happens with the scale command) called on the canvas is completely ignored for any parameter. I also tried to use:
c.drawColor(Color.BLACK)
instead of
c.drawBitmap(temp, 0, 0, null);
to paint all the canvas and it confirms that the commands are ignored.
Try this:
Canvas c = new Canvas(target);
c.rotate(rotationAngle, centerX, centerY);
c.drawBitmap(source, null);
Hope this helps :)
int count = canvas.save();
canvas.rotate(rotationAngle, centerX, centerY);
c.drawBitmap(source, null);
canvas.restoreToCount(count);
I am saving an image from the camera that was in landscape mode. so it gets saved in landscape mode and then i apply an overlay onto it that too is in landscape mode. I want to rotate that image and then save. e.g. if i have this
I want to rotate clockwise by 90 degrees once and make it this and save it to sdcard:
How is this to be accomplished?
void rotate(float x)
{
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.tedd);
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
matrix.postRotate(x);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,width, height, matrix, true);
iv.setScaleType(ScaleType.CENTER);
iv.setImageBitmap(resizedBitmap);
}
Check this
public static Bitmap rotateImage(Bitmap src, float degree)
{
// create new matrix
Matrix matrix = new Matrix();
// setup rotation degree
matrix.postRotate(degree);
Bitmap bmp = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, true);
return bmp;
}
You can use the Canvas API to do that. Note that you need to switch width and height.
final int width = landscapeBitmap.getWidth();
final int height = landscapeBitmap.getHeight();
Bitmap portraitBitmap = Bitmap.createBitmap(height, width, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(portraitBitmap);
c.rotate(90, height/2, width/2);
c.drawBitmap(landscapeBitmap, 0,0,null);
portraitBitmap.compress(CompressFormat.JPEG, 100, stream);
Use a Matrix.rotate(degrees) and draw the Bitmap to it's own Canvas using that rotating matrix. I don't know though if you might have to make a copy of the bitmap before drawing.
Use Bitmap.compress(...) to compress your bitmap to an outputstream.
The solution of Singhak works fine.
In case you need fit the size of result bitmap (perhaps for ImageView) you can expand the method as follows:
public static Bitmap rotateBitmapZoom(Bitmap bmOrg, float degree, float zoom){
Matrix matrix = new Matrix();
matrix.postRotate(degree);
float newHeight = bmOrg.getHeight() * zoom;
float newWidth = bmOrg.getWidth() / 100 * (100.0f / bmOrg.getHeight() * newHeight);
return Bitmap.createBitmap(bmOrg, 0, 0, (int)newWidth, (int)newHeight, matrix, true);
}