Hi I want to convert String to Bitmap and all things are good but I don't know how to set the result Image to fit the text .
How can I do that ?
Here is my code:
public Bitmap textAsBitmap(String text, float textSize, float stroke,
int color, Typeface typeface) {
TextPaint paint = new TextPaint();
paint.setColor(color);
paint.setTextSize(textSize);
paint.setStrokeWidth(stroke);
paint.setTypeface(typeface);
paint.setAntiAlias(true);
paint.setTextAlign(Paint.Align.LEFT);
float baseline = (int) (-paint.ascent() + 3f);
StaticLayout staticLayout = new StaticLayout(text, 0, text.length(),
paint, 435, android.text.Layout.Alignment.ALIGN_NORMAL, 1.0f,
1.0f, false);
int linecount = staticLayout.getLineCount();
int height = (int) (baseline + paint.descent() + 3) * linecount + 10;
Bitmap image = Bitmap
.createBitmap(****MY WIDTH***, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
canvas.drawARGB(0xFF, 0xFF, 0xFF, 0xFF);
staticLayout.draw(canvas);
return image;
}
I even tried this but it doesn't work properly:
final Rect bounds = new Rect();
paint.getTextBounds(text, 0, text.length(), bounds);
Bitmap image = Bitmap
.createBitmap(bounds.width(), height, Bitmap.Config.ARGB_8888);
please help!
Try this:
canvas.drawColor(Color.BLUE);
Instead of:
canvas.drawARGB(0xFF, 0xFF, 0xFF, 0xFF);
You should try this one
public String BitMapToString(Bitmap bitmap) {
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArray);
byte[] b = byteArray.toByteArray();
String result = Base64.encodeToString(b, Base64.DEFAULT);
return result;
}
Hope this will help!!!
Related
I need to change an image, from circle to normal square.
I'm a beginner a few weeks in programming,
I'm 2 days stopped in this code, does anyone know how to change?
I already tried everything, but I could not solve
I do not understand anything about canvas, I've already studied to solve this problem, but I'm still not able to
public static Bitmap getCircleBitmap(Bitmap bitmap) {
final int scaledWidth = 100;
final int scaledHeight = 100;
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
Bitmap output;
Rect srcRect, dstRect;
float r;
final int width = bitmap.getWidth();
final int height = bitmap.getHeight();
if (width > height) {
output = Bitmap.createBitmap(height, height, Bitmap.Config.ARGB_8888);
int left = (width - height) / 2;
int right = left + height;
srcRect = new Rect(left, 0, right, height);
dstRect = new Rect(0, 0, height, height);
r = height / 2;
} else {
output = Bitmap.createBitmap(width, width, Bitmap.Config.ARGB_8888);
int top = (height - width) / 2;
int bottom = top + width;
srcRect = new Rect(0, top, width, bottom);
dstRect = new Rect(0, 0, width, width);
r = width / 2;
}
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawCircle(r, r, r, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, srcRect, dstRect, paint);
bitmap.recycle();
return output;
}
public static Bitmap getBitmapFromVectorDrawable(Context context, int drawableId) {
Drawable drawable = AppCompatResources.getDrawable(context, drawableId);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
drawable = (DrawableCompat.wrap(drawable)).mutate();
}
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}
}
If you look at your code, towards the end of method getCircleBitmap() you have the below line of code:
canvas.drawCircle(r, r, r, paint);
That's the one drawing the circle image for you using DrawCircle.
What you can do is, replace it with DrawRect. That should do that trick for you.
However, if you need to just draw a square image from a vector then you can use a standard ImageView straightaway and use the vector as image resource.
here is my code :
ImageView mImageView = (ImageView)findViewById(R.id.imageView1);
// Bitmap bmp =drawTextToBitmap(this,R.drawable.man,"Hello Android");
Bitmap bmp =drawTextArrayToBitmap(this,R.drawable.man,"Smile");
mImageView.setImageBitmap(bmp);
now here is my method :
public Bitmap drawTextArrayToBitmap(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();
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.rgb(110,110, 110));
paint.setTextSize((int) (12 * scale));
paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);
Rect bounds = new Rect();
paint.getTextBounds(mText, 0, mText.length(), bounds);
/* int x = (bitmap.getWidth() - bounds.width())/6;
int y = (bitmap.getHeight() + bounds.height())/5;*/
int x = 100, y = 100;
for(int i=0;i<20;i++)
{
canvas.drawText(mText, x * scale, y * scale, paint);
}
return bitmap;
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
}
I am working on an android application like image filter I want to make an image like this after using a filter over an image
After searching on StackOverflow I got this solution only and this is not like as I want to implement: I got like this
canvas.drawText("This is", 100, 100, mTextPaint);
canvas.drawText("multi-line", 100, 150, mTextPaint);
canvas.drawText("text", 100, 200, mTextPaint);
I do not want to do like this : please help me I would approciate your answers and suggestion
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;
}
I need to create shadow effect for an image .
private static Bitmap getDropShadow3(Bitmap bitmap) {
if (bitmap==null) return null;
int think = 6;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int newW = w - (think);
int newH = h - (think);
Bitmap.Config conf = Bitmap.Config.ARGB_8888;
Bitmap bmp = Bitmap.createBitmap(w, h, conf);
Bitmap sbmp = Bitmap.createScaledBitmap(bitmap, newW, newH, false);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Canvas c = new Canvas(bmp);
// Right
Shader rshader = new LinearGradient(newW, 0, w, 0, Color.GRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
paint.setShader(rshader);
c.drawRect(newW, think, w, newH, paint);
// Bottom
Shader bshader = new LinearGradient(0, newH, 0, h, Color.GRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
paint.setShader(bshader);
c.drawRect(think, newH, newW , h, paint);
//Corner
Shader cchader = new LinearGradient(0, newH, 0, h, Color.LTGRAY, Color.LTGRAY, Shader.TileMode.CLAMP);
paint.setShader(cchader);
c.drawRect(newW, newH, w , h, paint);
c.drawBitmap(sbmp, 0, 0, null);
return bmp;
}
i used the above code, and i get two sides (Right, bottom) shadow effect . How can i make the effect in all sides including (top,Left)?
the method that you are using; may cause some problems with a certain type of images (irregular ones)
try this method instead (much much easier to understand and more flexible):
public Bitmap addShadowToBitmap(final Bitmap bm, final int dstHeight, final int dstWidth, int color, int size, float dx, float dy) {
final Bitmap mask = Bitmap.createBitmap(dstWidth, dstHeight, Config.ALPHA_8);
final Matrix scaleToFit = new Matrix();
final RectF src = new RectF(0, 0, bm.getWidth(), bm.getHeight());
final RectF dst = new RectF(0, 0, dstWidth - dx, dstHeight - dy);
scaleToFit.setRectToRect(src, dst, ScaleToFit.CENTER);
final Matrix dropShadow = new Matrix(scaleToFit);
dropShadow.postTranslate(dx, dy);
final Canvas maskCanvas = new Canvas(mask);
final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
maskCanvas.drawBitmap(bm, scaleToFit, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_OUT));
maskCanvas.drawBitmap(bm, dropShadow, paint);
final BlurMaskFilter filter = new BlurMaskFilter(size, Blur.NORMAL);
paint.reset();
paint.setAntiAlias(true);
paint.setColor(color);
paint.setMaskFilter(filter);
paint.setFilterBitmap(true);
final Bitmap ret = Bitmap.createBitmap(dstWidth, dstHeight, Config.ARGB_8888);
final Canvas retCanvas = new Canvas(ret);
retCanvas.drawBitmap(mask, 0, 0, paint);
retCanvas.drawBitmap(bm, scaleToFit, null);
mask.recycle();
return ret;
}
call it through:
addShadowToBitmap(arg0, arg1, arg2, arg3, arg4, arg5, arg6);
and it will return you a bitmap.
hope this will help.
Ahmad's code was not quite right for me. I augmented his code to determine w/h of returned bitmap based on the dx/dy and shadow size. This code worked for me with a bitmap that was a signature of a user.
public Bitmap addShadowToBitmap(final Bitmap bm, int color, int size, int dx, int dy) {
int dstWidth = bm.getWidth() + dx + size/2;
int dstHeight = bm.getHeight() + dy + size/2;
final Bitmap mask = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ALPHA_8);
final Canvas maskCanvas = new Canvas(mask);
final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
maskCanvas.drawBitmap(bm, 0, 0, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
maskCanvas.drawBitmap(bm, dx, dy, paint);
final BlurMaskFilter filter = new BlurMaskFilter(size, BlurMaskFilter.Blur.NORMAL);
paint.reset();
paint.setAntiAlias(true);
paint.setColor(color);
paint.setMaskFilter(filter);
paint.setFilterBitmap(true);
final Bitmap ret = Bitmap.createBitmap(dstWidth, dstHeight, Bitmap.Config.ARGB_8888);
final Canvas retCanvas = new Canvas(ret);
retCanvas.drawBitmap(mask, 0, 0, paint);
retCanvas.drawBitmap(bm, 0, 0, null);
mask.recycle();
return ret;
}
I have some code where I'm drawing my text on bitmap (canvas)
canvas.drawTextOnPath(Text, textPath[count], gipa, -10, text);
Please tell me, it's possible to draw this text in path(textPath) with background color?
it's full function for drawing only text
public void drawText(float x,float y ,String Text,Canvas canvas,Paint paint1 ,int count )
{
float xren =text.measureText(Text.trim());
canvas.drawTextOnPath(Text, textPath[count], gipa, -10, text);
}
Using this function I'm drawing text on my canvas. so how to modify this function for drawing this text with background?
Most likely two steps are needed here. you would draw a line along path first with color for background and then draw the text as indicated. Set the thickness of the line with a paint object. Also, changing the style of the paint can help with the effect. try FILL, STROKE or FILL_AND_STROKE for different effects.
mpaint.setStyle(Paint.Style.STROKE);
mpaint.setStrokeWidth(strokeWidth);
Added sample to draw a path(rectangle) with red color:
Paint mPaint = new Paint();
mPaint.setColor(Color.RED);
Path mPath = new Path();
RectF mRectF = new RectF(20, 20, 240, 240);
mPath.addRect(mRectF, Path.Direction.CCW);
mPaint.setStrokeWidth(20);
mPaint.setStyle(Paint.Style.STROKE);
canvas.drawPath(mPath, mPaint);
Then draw text along same path (blue color):
mPaint.setColor(Color.BLUE);
mPaint.setStrokeWidth(0);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setTextSize(20);
canvas.drawTextOnPath("Draw the text, with origin at (x,y), using the specified paint, along the specified path.", mPath, 0, 5, mPaint);
If you want to make like this then implement below code snippet:
/**
* PUT THIS METHOD FOR IMPLEMENT WATER-MARK IN COMMON FILE
*/
public static Bitmap waterMark(Bitmap src, String watermark) {
//get source image width and height
int w = src.getWidth();
int h = src.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
Paint.FontMetrics fm = new Paint.FontMetrics();
paint.setColor(Color.WHITE);
paint.getFontMetrics(fm);
int margin = 5;
canvas.drawRect(50 - margin, 50 + fm.top - margin,
50 + paint.measureText(watermark) + margin, 50 + fm.bottom
+ margin, paint);
paint.setColor(Color.RED);
canvas.drawText(watermark, 50, 50, paint);
return result;
}
// To Get Bitmap from URI:
private Bitmap getBitmapFromUri(String photoPath) {
Bitmap image = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
return bitmap;
}
// Save Image :
private String SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/shareImage");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 20, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
// Call like this :
Bitmap bitmap = getBitmapFromUri(attachment.get(i).getPath()); // Enter here your Image path
Bitmap bitmapp = waterMark(bitmap, "ENTER YOUR TEXT FOR WATERMARK LABEL");
String path = SaveImage(bitmapp);
Uri uri = Uri.fromFile(new File(path));
Here at last from uri you can get a new implemented watermark image.
Hope this helps you.
I believe this solution is better and more flexible than drawPath.
Use this to calculate the size of the text background:
private #NonNull Rect getTextBackgroundSize(float x, float y, #NonNull String text, #NonNull TextPaint paint) {
Paint.FontMetrics fontMetrics = paint.getFontMetrics();
float halfTextLength = paint.measureText(text) / 2 + 5;
return new Rect((int) (x - halfTextLength), (int) (y + fontMetrics.top), (int) (x + halfTextLength), (int) (y + fontMetrics.bottom));
}
Then draw the background as a Rect:
Rect background = getTextBackgroundSize(x, y, text, textPaint);
canvas.drawRect(background, bkgPaint);
canvas.drawText(text, x, t, textPaint);
this method i created , it will give you better idea how easily you can do this
public static Drawable getTextToDrawable(final String sText, final float textSize, final int textColor, final int bgColor, final int imageSize) {
Shape shape = new Shape() {
#Override
public void draw(Canvas canvas, Paint paint) {
paint.setTextSize(spToPixel(textSize));
int ivImageSize = SUtils.dpToPx(imageSize);
paint.setTextAlign(Paint.Align.LEFT);
float baseline = -paint.ascent(); // ascent() is negative
int width = (int) (paint.measureText(sText)); // round
int height = (int) (baseline + paint.descent());
Bitmap image = Bitmap.createBitmap(ivImageSize, (int) (ivImageSize), Bitmap.Config.ARGB_8888);
canvas.drawBitmap(image, ivImageSize, ivImageSize, paint);
paint.setColor(bgColor);
if (sText != null) {
if (sText.length() < 3) {
canvas.drawCircle(ivImageSize / 2, ivImageSize / 2, ivImageSize / 2, paint);
paint.setColor(textColor);
canvas.drawText(sText, (ivImageSize - width) / 2, (height+baseline)/2, paint);
} else {
canvas.drawRect(0, 0, ivImageSize, height, paint);
paint.setColor(textColor);
canvas.drawText(sText, (ivImageSize - width) / 2, baseline, paint);
}
}
}
};
return new ShapeDrawable(shape);
}