I'd like to convert a dynamic string to Bitmap and save it on disk. The image should appear like the image below with the corner around the string.
I couldnt find a way to direct convert a String to bitmap, I tried to create a textView and convert it to bitmap, but it dont work properly.
Obs: I saw some questions that is similar, but they really don't have a solution to this question.
public static String StringToBitMap(Context context, String name){
TextView textView = new TextView(context);
textView.setText(name);
try{
int w = textView.getWidth();
int h = textView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(w, h,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.WHITE);
Drawable bgDrawable = textView.getBackground();
if (bgDrawable!=null) {
bgDrawable.draw(canvas);
}
else {
canvas.drawColor(Color.WHITE);
}
textView.draw(canvas);
FileOutputStream out = null;
File file = null;
try {
String path = Environment.getExternalStorageDirectory().toString();
file = new File(path + "/Download/", "item.png");
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
out.close();
MediaStore.Images.Media.insertImage(context.getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file.getAbsolutePath();
}catch(Exception e){
e.getMessage();
return null;
}
}
I just found the solution:
public static String StringToBitMap(Context context, String name){
try{
// Create bitmap
Bitmap bitmap = Bitmap.createBitmap(250, 16,Bitmap.Config.ARGB_8888);
bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(0xffffffff);
// new antialised Paint
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
// text color - #3D3D3D
paint.setColor(Color.BLACK);
// text size in pixels
paint.setTextSize(12);
// draw text to the Canvas center
Rect bounds = new Rect();
paint.getTextBounds(name, 0, name.length(), bounds);
int x = (bitmap.getWidth() - bounds.width())/2;
int y = (bitmap.getHeight() + bounds.height())/2;
canvas.drawText(name, x, y, paint);
paint.setColor(Color.BLACK);
paint.setStrokeWidth(3);
paint.setStyle(Paint.Style.STROKE);
// draw corner to the Canvas
canvas.drawRect(x - 5, 0.0f, x + bounds.width() + 5, 16.0f, paint);
// save on disk
FileOutputStream out = null;
File file = null;
try {
String path = Environment.getExternalStorageDirectory().toString();
file = new File(path + "/Download/", "item.png");
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
out.close();
MediaStore.Images.Media.insertImage(context.getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return file.getAbsolutePath();
}catch(Exception e){
e.getMessage();
return null;
}
}
Related
How to use specific width and height for bitmap on saving framelayout to image?
Check following code
public Bitmap convertFrameToBitmap(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
ry {
FileOutputStream output = new FileOutputStream(getActivity().getFilesDir() + File.separator+ image.png");
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
output.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I am trying to compress a bitmap, but getting a null pointer exception..the logcat is displaying uncaught exception
Bitmap bitmap = BitmapFactory.decodeByteArray(imageAsBytes , 0, imageAsBytes .length);
Bitmap bPNGcompress =codec(bitmap, Bitmap.CompressFormat.PNG, 0);
Bitmap scaled = bPNGcompress.createScaledBitmap( bPNGcompress, 100, 100, true );
method implementation
private static Bitmap codec(Bitmap map, Bitmap.CompressFormat format,
int quality) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
map.compress(format, quality, os);
try {
os.flush();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] array = os.toByteArray();
return BitmapFactory.decodeByteArray(array, 0, array.length);
}
Please try this,
private static Bitmap codec(Bitmap src, Bitmap.CompressFormat format,int quality)
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
src.compress(format, quality, os);
byte[] array = os.toByteArray();
return BitmapFactory.decodeByteArray(array, 0, array.length);
}
private static class SampleView extends View {
// CONSTRUCTOR
public SampleView(Context context) {
super(context);
setFocusable(true);
}
#Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
canvas.drawColor(Color.GRAY);
// you need to insert some image flower_blue into res/drawable folder
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.flower_blue);
// Best of quality is 80 and more, 3 is very low quality of image
Bitmap bJPGcompress = codec(b, Bitmap.CompressFormat.JPEG, 3);
// get dimension of bitmap getHeight() getWidth()
int h = b.getHeight();
canvas.drawBitmap(b, 10,10, paint);
canvas.drawBitmap(bJPGcompress, 10,10 + h + 10, paint);
}
}
when I screen shot the map. I cannot success to shot the all screen.it only show the path.
I want to know what my problem is on my code. I hope someone can help me. thank you
It is my result:
// Screen shot
private static Bitmap takeScreenShot(Activity activity) {
// View to shot View
View view = activity.getWindow().getDecorView();
//View view = getPopupViews(getDecorViews())[0];
Log.i("ABC", view.getClass().getName());
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
// the height
Rect frame = new Rect();
view.getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
System.out.println(statusBarHeight);
// width and height
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay().getHeight();
// del the state bar
// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return b;
}
// save image to sdcard
private static void savePic(Bitmap b, String strFileName) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(strFileName);
if (null != fos) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void shoot() {
shoot(this);
}
// call function
public static void shoot(Activity a) {
savePic(takeScreenShot(a), "data/data/com.example.map/"+number+".png");
}
try this code, and pass mapView in this
public final static Bitmap takeScreenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
private Bitmap getMapImage() {
MapController mc = mapView.getController();
mc.setCenter(GEO_POINT);
mc.setZoom(ZOOM_LEVEL);
/* Capture drawing cache as bitmap */
mapView.setDrawingCacheEnabled(true);
Bitmap bmp = Bitmap.createBitmap(mapView.getDrawingCache());
mapView.setDrawingCacheEnabled(false);
return bmp;
}
private void saveMapImage() {
String filename = "SCREEN_SHOT.png";
File f = new File(getExternalFilesDir(null), filename);
FileOutputStream out = new FileOutputStream(f);
Bitmap bmp = getMapImage();
bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
out.close();
}
I want to merge two bitmaps, here is my code
// Camera arg conversion to Bitmap
Bitmap cameraBitmap = BitmapFactory.decodeByteArray(arg0, 0,
arg0.length);
Bitmap back = Bitmap.createBitmap(cameraBitmap.getWidth(),
cameraBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas cam = new Canvas(back);
cam.drawBitmap(cameraBitmap, matrix, null);
// FrameLayout to Bitmap
FrameLayout mainLayout = (FrameLayout) findViewById(R.id.frame);
Bitmap foreground = Bitmap.createBitmap(mainLayout.getWidth(),
mainLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(foreground);
mainLayout.draw(c);
Bitmap cs = null;
cs = Bitmap.createBitmap(foreground.getWidth(), cameraBitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(cameraBitmap, 0f, 0f, null);
comboImage.drawBitmap(foreground, 0f, cameraBitmap.getHeight(), null);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
if (fos != null) {
cs.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
The camera image should become background, and foreground as top image. I've tried from
Combining 2 Images in Android using Canvas but it didn't help me. Any idea.? Thanks
From your example, you forgot to add the next lines:
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, 0f, c.getHeight(), null);
In your example above you don't draw your image in the canvas, and that is the problem.
You can think that your canvas i your sketchbook. For now you didn't paint anything, and you ask yourself, way I can't see any colors.
So, for my advice, first create the two bitmaps, then, do the next thing:
c.drawBitmap(cameraBitmap, top point, left point, null);
c.drawBitmap(foreground, top point, left point, null);
You can also do this by first create the drawable objects from your bitmaps, like in the next code:
Drawable cameraBitmap = BitmapDrawable(cameraBitmap);
Drawable foreground= BitmapDrawable(foreground);
Then when you have the drawable objects, you can set thier bounds, and that way you set where do you want to show that image.
cameraBitmap.setBounds(left, top, right, bottom);
foreground.setBounds(left, top, right, bottom);
and finally draw that on the canvas:
cameraBitmap.draw(canvas);
foreground.draw(canvas);
EDIT:
This is an example, use this to understand your implementation:
Bitmap bitmap = null;
try {
bitmap = Bitmap.createBitmap(500, 500, Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
Resources res = getResources();
Bitmap bitmap1 = BitmapFactory.decodeResource(res, R.drawable.test1); //blue
Bitmap bitmap2 = BitmapFactory.decodeResource(res, R.drawable.test2); //green
Drawable drawable1 = new BitmapDrawable(bitmap1);
Drawable drawable2 = new BitmapDrawable(bitmap2);
drawable1.setBounds(100, 100, 400, 400);
drawable2.setBounds(150, 150, 350, 350);
drawable1.draw(c);
drawable2.draw(c);
} catch (Exception e) {
}
return bitmap;
This is what I get from the code above:
Merging Two Bitmap vertically when one is large and second is small
follow this method
public Bitmap finalcombieimage(Bitmap c, Bitmap s) {
Bitmap cs = null;
DisplayMetrics metrics = getBaseContext().getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
Rect dest1 = new Rect(0, 0, width, height); // left,top,right,bottom
comboImage.drawBitmap(c, null, dest1, null);
Rect dest2 = new Rect(0, height-400 / 2, width, height);
comboImage.drawBitmap(s, null, dest2, null);
return cs;
}
Please note that the BitmapDrawable(Bitmap) has been deprecated. Kinldy check this for the alternative.
BitmapDrawable(Bitmap bitmap)
This constructor was deprecated in API level 4. Use BitmapDrawable(Resources, Bitmap) to ensure that the drawable has correctly set its target density.
Resize watermark image same size as original image
Uri bmpUri1 = getLocalBitmapUri(ivImage);
Uri bmpUri2 = getLocalBitmapUri(watermark_imageview);
try {
bm1 = BitmapFactory.decodeStream(
getContentResolver().openInputStream(bmpUri1));
bm2 = BitmapFactory.decodeStream(
getContentResolver().openInputStream(bmpUri2));
Bitmap bmOverlay = Bitmap.createBitmap(bm1.getWidth(), bm1.getHeight(), bm1.getConfig());
bm2 = Bitmap.createScaledBitmap(bm2, bm1.getWidth(), bm1.getHeight(),
true);
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bm1, 0,0, null);
canvas.drawBitmap(bm2, 0,0, null);
watermarkimage.setVisibility(View.GONE);
im =new ImageView(ImageClick.this);
im.setImageBitmap(bmOverlay);
bmpUri = getLocalBitmapUri(im);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
private Uri getLocalBitmapUri(ImageView imageView) {
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable){
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
I'm using the code below. My app was able to draw on the canvas and save it.
But what I want to do is make an image as the background of the canvas so when I save it, it will look like an image with the user's drawing on top of it.
Thank you so much for any help! :)
#Override
public void run() {
Canvas canvas = null;
while (_run){
if(isDrawing == true){
try{
canvas = mSurfaceHolder.lockCanvas(null);
if(mBitmap == null){
mBitmap = Bitmap.createBitmap (1, 1, Bitmap.Config.ARGB_8888);
}
final Canvas c = new Canvas (mBitmap);
c.drawColor(0, PorterDuff.Mode.CLEAR);
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
canvas.drawColor(0xffffffff);
commandManager.executeAll(c,previewDoneHandler);
previewPath.draw(c);
canvas.drawBitmap (mBitmap, 0, 0,null);
} finally {
mSurfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
Try this stuff,
This will return a Bitmap that will be a Merged one of two Bitmap Images, also it will save in the SDCard.
public Bitmap combineImages(Bitmap c, Bitmap s) {
Bitmap cs = null;
int width, height = 0;
if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight();
} else {
width = s.getWidth() + s.getWidth();
height = c.getHeight();
}
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0, 0, null);
comboImage.drawBitmap(s, 100, 300, null);
/******
*
* Write file to SDCard
*
* ****/
String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png";
OutputStream os = null;
try {
os = new FileOutputStream(Environment.getExternalStorageDirectory()
+ "/"+tmpImg);
cs.compress(CompressFormat.PNG, 100, os);
} catch (IOException e) {
Log.e("combineImages", "problem combining images", e);
}
return cs;
}
For any view that you are creating, you can create a bitmap of what it is currently displaying.
use:
view.setDrawingCacheEnabled(true);
Bitmap bitmap=view.getDrawingCache();
Does this help you in achieving what you want ?
*be sure to recycle these bitmaps when you are done.
bitmap.recycle();