I am developing an application where I need to generate an Image from text and store that Image to the SDCard.
Can anyone tell me a library(just like textimagegenerator for java) I need android compatible library or source which I can use for this?
TextView textView = new TextView(activity.getContext());
textView.setText("Hello World");
textView.setDrawingCacheEnabled(true);
textView.destroyDrawingCache();
textView.buildDrawingCache();
Bitmap bitmap = getTransparentBitmapCopy(textView.getDrawingCache());
private Bitmap getTransparentBitmapCopy(Bitmap source)
{
int width = source.getWidth();
int height = source.getHeight();
Bitmap copy = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
int[] pixels = new int[width * height];
source.getPixels(pixels, 0, width, 0, 0, width, height);
copy.setPixels(pixels, 0, width, 0, 0, width, height);
return copy;
}
You can use android.graphics.Canvas.drawText() for this.
Try to do this
Got the controls.
Button b1=(Button)findViewById(R.id.button1);
EditText ed1=(EditText)findViewById(R.id.editText1);
String msg=ed1.getText().toString();
Create the bitmap, canvas, paint,and invoke drawText function:
Bitmap bitmap = Bitmap.createBitmap(300, 400, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawColor(Color.CYAN);
Paint paint = new Paint();
paint.setTextAlign(Align.LEFT);// 若设置为center,则文本左半部分显示不全 paint.setColor(Color.RED);
paint.setAntiAlias(true);// 消除锯齿
paint.setTextSize(20);
canvas.drawText(msg, 20, 30, paint) ;
canvas.save(Canvas.ALL_SAVE_FLAG);
canvas.restore();
Save the image
String path = Environment.getExternalStorageDirectory() + "/abc.png";
FileOutputStream fos = new FileOutputStream(new File(path));
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
Assuming you have a text view or an image view, you will do this:
TextView tv = (TextView)findViewById(R.id.textview);
Bitmap bp;
bp = loadBitmapFromView(tv);
ImageView iv = new ImageView(this);
iv.setImageBitmap(bp);
try {
OutputStream fOut = null;
String path = "/sdcard/";
File file = new File(path, "imagename here.jpg");
fOut = new FileOutputStream(file);
getImageBitmap(bp).compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
} catch (Exception e) {
e.printStackTrace();
}
be sure to put this in your androidmanifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Yo can have a look at this "Android save view to jpg or png" post:
Hope this helps
Related
here i have a quick question on webview.
My requirement is capture the webview and save the file in sdcard to that i used below code.
Below code for generating Bitmap from webview
Webview to Bitmap :
webview.measure(MeasureSpec.makeMeasureSpec(
MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
webview.layout(0, 0, webview.getMeasuredWidth(),
webview.getMeasuredHeight());
webview.setDrawingCacheEnabled(true);
webview.buildDrawingCache();
bitmap = Bitmap.createBitmap(webview.getMeasuredWidth(),
webview.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas bigcanvas = new Canvas(bitmap);
Paint paint = new Paint();
int iHeight = bitmap.getHeight();
bigcanvas.drawBitmap(bitmap, 0, iHeight, paint);
webview.draw(bigcanvas);
}
catch (Exception e)
{
e.printStackTrace();
}
webview.setDrawingCacheEnabled(false);
below code for to save the file in memory for that
To save as file :
File myDir = new File(Environment.getExternalStorageDirectory(), "Sample");
if (myDir.exists())
{
}
else
{
myDir.mkdir();
}
String fname = "sample" + ".png";
file1 = new File(myDir, fname);
if(bitmap!=null)
{
try
{
FileOutputStream out = new FileOutputStream(file1);
bitmap.compress(Bitmap.CompressFormat.PNG, 10, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}}
but here webview loading fine but not capturing completely in android 5.0(lollipop) as shown in below image
how can i resolve this issue? please give me suggestions or some snippet of code.
Thanks in advance..
U can draw the view on a canvas like this:
Bitmap mBitmap;
Layout webViewContainer
mBitmap = Bitmap.createBitmap(webViewContainer.getWidth(), webViewContainer.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(mBitmap);
webViewContainer.draw(canvas);
You need to call WebView.enableSlowWholeDocumentDraw() before creating any WebViews. That is, if you have any WebViews in your layout, make sure you call this method before calling setContentView() in your onCreate() shown below.
if (Build.VERSION.SDK_INT >= 21) {
webview.enableSlowWholeDocumentDraw ();
}
its working fine for me..
I am trying to open a saved image in the gallery, and after writing some text on this opened image, trying to close it. But so far, it doesn't work. Could you tell me what I am doing wrong please?
**I checked the path, it is correct. Here is the my code :
String path = android.os.Environment.getExternalStorageDirectory().toString() + "/DCIM/100LGDSC/";
String pathiki = path+filename;
Log.d("pathiki:",pathiki);
try {
Bitmap bm = BitmapFactory.decodeFile(pathiki);
Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);
Paint paint = new Paint();
paint.setStyle(Style.FILL);
paint.setColor(Color.WHITE);
paint.setTypeface(tf);
paint.setTextAlign(Align.CENTER);
paint.setTextSize(14);
Canvas canvas = new Canvas(bm);
canvas.drawText("bla bla bla", 100, 100, paint);
OutputStream fOut = new FileOutputStream(new File(pathiki));
bm.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
} catch (Exception e) {
// TODO: handle exception
e.toString();
}
BitmapFactory.decodeFile always returns an immutable bitmap. Use Bitmap.copy to make a copy of bitmap which is mutable. Now perform modifications on the copied bitmap.
Bitmap bm = BitmapFactory.decodeFile(pathiki).copy(Bitmap.Config.ARGB_8888, true);
Update the exception handler code. Either log e.getMessage() to logcat or use e.printStackTrace().
I have checked many discussion but i can't seem to find an answer. How can i crop and large image taken by a camera and crop it to a 640x640 pixel size? Im returning a URI
EDIT: I would like to allow the user to crop the image!
Another solution would be to use the createScaledBitmap people use to create thumbnails.
byte[] imageData = null;
try
{
final int THUMBNAIL_SIZE = 64;
FileInputStream fis = new FileInputStream(fileName);
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, THUMBNAIL_SIZE, THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
}
catch(Exception ex) {
}
Your bitmap imageBitmap would probably have to come directly from your camera instead of a file, but the general idea stays the same.
You may use
private Bitmap crop(Bitmap src, int x, int y, int width, int height) {
Bitmap dst = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(dst);
canvas.drawBitmap(src, new Rect(0, 0, src.getWidth(), src.getHeight()),
new Rect(x, y, width, height), null);
return dst;
}
Type arguments are self explanatory.
Good luck.
Try this code, using the intent object:
intent.setType("image/*");
intent.putExtra("outputX", int_Height_crop);
intent.putExtra("outputY", int_Width_crop);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
use the below code
You can use this link also for your reference
Click Crop image using rectengle!
int targetWidth = 640;
int targetHeight = 640;
Bitmap targetBitmap = Bitmap.createBitmap(
targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addRect(rectf, Path.Direction.CW);
canvas.clipPath(path);
canvas.drawBitmap(sourceBitmap,
new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight()),
new Rect(0, 0, targetWidth, targetHeight), null);
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
imageView.setImageBitmap(targetBitmap);
I have the following code for creating a bitmap:
public PixelMapper(Path inputPath){
RectF src = new RectF();
inputPath.computeBounds(src, true);
int width = (int)src.width()+1;
int height = (int)src.height()+1;
largeBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
Paint canvasPaint = new Paint();
canvasPaint.setAntiAlias(false);
canvasPaint.setColor(Color.BLACK);
canvasPaint.setStyle(Style.STROKE);
canvasPaint.setStrokeWidth(5);
Canvas canvas = new Canvas(largeBitmap);
canvas.drawPath(inputPath, canvasPaint);
bitmap = Bitmap.createScaledBitmap(largeBitmap, SIDE_OF_BITMAP, SIDE_OF_BITMAP, true);
bitmap = Bitmap.createBitmap(bitmap);//so that a immutable bitmap is created
drawPixelMap();
}
public void drawPixelMap(){
for(int x=0; x<bitmap.getWidth(); x++){
String msg="";
for(int y=0; y<bitmap.getHeight(); y++){
msg = Integer.toHexString( bitmap.getPixel(x,y) );
Log.v("bitmap", msg);
}
}
}
int[] pixels = new int[64];
bitmap.getPixels(pixels, 0, bitmap.getWidth(), 0, 0, SIDE_OF_BITMAP, SIDE_OF_BITMAP);
bitmap.setPixels(pixels, 0, 8, 0, 0, 8, 8);
for ( int pixel : pixels)
Log.v("bitmap", Integer.toHexString(pixel) );
The problem is that all the log messages are "0": both getPixel and getPixels return "0". What is worse is that if I remove the line bitmap.getPixels(...); and leave the bitmap.setPixels(...) line,the image is still drawn as before. It seems that the bitmap variable is just a reference and a bitmap doesn't exist, and for some reason, I am unable to get those pixels.
I know the bitmap is created as required as I am able to view it on a ImageView. It shows black and white pixels with a few grey ones too. Code:
Bitmap newBitmap = Bitmap.createScaledBitmap(bitmap, 128, 128, false);
imageView1.setImageBitmap(newBitmap);
The SIDE_OF_BITMAP = 8, all classes (Path, Bitmap, Canvas) are of android.
I tried saving the bitmap to file with the following code:
public String saveToStorage(String fileName){
if( !storageDir.exists() )
storageDir.mkdirs();
File file = new File(storageDir, fileName + ".png");
try{
OutputStream out = new FileOutputStream(file);
boolean result = bitmap.compress(CompressFormat.PNG, 100, out);
out.close();
return Boolean.toString(result);
}
catch (FileNotFoundException e){
Log.e("save", "cannot save file", e);
return "File not found exception";
}
catch (IOException e){
Log.e("save", "IO error", e);
return "IO Exception";
}
}
but it returns "false" i.e. the bitmap.compress method returns false. Please give me any help at all, not necessarily sample code.
I found my mistake. It lies in the line
largeBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
The Bitmap.Config.ALPHA_8 only creates a mask. It does not create actual pixels. That is why I was getting the erroneous results. However, when I was setting it to a ImageView I was getting the required result because its background (by default) is white.
I solved my problem by changing the Bitmap.Config.ALPHA_8 to Bitmap.Config.ARGB_8888
The line
bitmap = Bitmap.createBitmap(bitmap);
creates a immutable bitmap of the same dimension/color depth, etc as the source bitmap, but not converting the source bitmap from mutable to immutable. So your new bitmap is blank.
You can first create a immutable bitmap using newBitmap = Bitmap.createBitmap(int[], int, int, Bitmap.Config), then create a canvas for it by canvas = new Canvas(newBitmap). Your bitmap can now be copied to newBitmap by canvas.drawBitmap(bitmap, 0, 0, null).
I want to draw text on image ( for saving that image with text ). i have image view i set bitmap to that image i want to Draw the text on image (text entered by user ). i tried this before saving.....
void saveImage() {
File myDir=new File("/sdcard/saved_images");
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);
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Xml code is..
<FrameLayout
android:id="#+id/framelayout"
android:layout_marginTop="30dip"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
<ImageView
android:id="#+id/ImageView01"
android:layout_alignParentTop="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
<TextView android:id="#+id/text_view2"
android:layout_marginTop="20dip"
android:layout_width="wrap_content"
android:text="SampleText"
android:textSize="12pt"
android:layout_alignTop="#+id/ImageView01"
android:layout_height="wrap_content"/>
</FrameLayout>
As suggested by Vladislav Skoumal, try this method:
public 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.rgb(110,110, 110));
// 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())/5;
canvas.drawText(mText, x * scale, y * scale, paint);
return bitmap;
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
call this method
Bitmap bmp =drawTextToBitmap(this,R.drawable.aa,"Hello Android");
img.setImageBitmap(bmp);
the output
Updated SaveImage() method, to support text drawing.
void saveImage() {
File myDir=new File("/sdcard/saved_images");
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);
// NEWLY ADDED CODE STARTS HERE [
Canvas canvas = new Canvas(originalBitmap);
Paint paint = new Paint();
paint.setColor(Color.WHITE); // Text Color
paint.setTextSize(12); // Text Size
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER)); // Text Overlapping Pattern
// some more settings...
canvas.drawBitmap(originalBitmap, 0, 0, paint);
canvas.drawText("Testing...", 10, 10, paint);
// NEWLY ADDED CODE ENDS HERE ]
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Let me know if this works for you.
Shash
You can extend a view to create a custom view. Something like
public class PieView extends View {
public PieView(Context context) {
super(context);
overlayBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.piechart_shade,
null);
overlayWidth = overlayBitmap.getWidth();
setLayoutParams(new LayoutParams(overlayWidth, overlayWidth));
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
In the ondraw method you can use canvas.drawBitmap and canvas.drawText to draw bitmaps and text.
This way you do not requirre a framelayout as everything is in a single custom view.
You can include this in your xml file as
<com.raj.PieView android:id="#+id/framelayout" android:layout_marginTop="30dip"
android:layout_height="fill_parent" android:layout_width="fill_parent"/>
create an empty bitmap
create a new Canvas object and pass this bitmap to it
call view.draw(Canvas) passing it the canvas object you just created. Refer Documentation of method for details.
Use Bitmap.compress() to write the contents of the bitmap to an OutputStream, file maybe.
Pseudo code:
Bitmap bitmap = Bitmap.createBitmap(200,200,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawText();
//necessary arguments and draw whatever you want. thes all are drawn on the bitmap.finally save this bitmap
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Inflate a text view over the image .
Refer http://www.android10.org/index.php/forums/43-view-layout-a-resource/715-tutorial-android-xml-view-inflation for a basic example.
This should be the easiest way.
LinearLayout lLayout;
lLayout = (LinearLayout)findViewById(R.id.layout1);
layout1 is the main layout.
final LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView tv = (TextView)inflater.inflate(R.layout.text, null);
lLayout.addView(tv);
I solve this problem (immutable file), but nothing is write in file... follow my code:
public static File writeOnImage(File file) throws IOException {
Bitmap originalBitmap = BitmapFactory.decodeFile(file.getPath());
originalBitmap = convertToMutable(originalBitmap);
FileOutputStream out = new FileOutputStream(file);
try {
Canvas canvas = new Canvas(originalBitmap);
Paint paint = new Paint();
paint.setColor(Color.BLACK);
paint.setStrokeWidth(12);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OVER));
canvas.drawBitmap(originalBitmap, 0, 0, paint);
canvas.drawText("Testing...", 10, 10, paint);
originalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
In case you using Glide to get the image, i modified #Dwivedi's answer to this (using kotlin) :
Glide.with(this)
.asBitmap()
.load("https://images.pexels.com/photos/1387577/pexels-photo-1387577.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260")
.into(object : CustomTarget<Bitmap>() {
override fun onLoadCleared(placeholder: Drawable?) {}
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
val bm = resource.copy(Bitmap.Config.ARGB_8888, true)
val tf = Typeface.create("Helvetica", Typeface.BOLD)
val paint = Paint()
paint.style = Paint.Style.FILL
paint.color = Color.WHITE
paint.typeface = tf
paint.textAlign = Paint.Align.LEFT
paint.textSize = dip(25).toFloat()
val textRect = Rect()
paint.getTextBounds("HELLO WORLD", 0, "HELLO WORLD".length, textRect)
val canvas = Canvas(bm)
//If the text is bigger than the canvas , reduce the font size
if (textRect.width() >= canvas.width - 4)
//the padding on either sides is considered as 4, so as to appropriately fit in the text
paint.textSize = dip(12).toFloat()
//Calculate the positions
val xPos = canvas.width.toFloat()/2 + -2
//"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
val yPos = (canvas.height / 2 - (paint.descent() + paint.ascent()) / 2) + 0
canvas.drawText("HELLO WORLD", xPos, yPos, paint)
binding.imageDrawable.setImageBitmap(bm)
}
})