Android add Text to Canvas fail - android

I am going to create a jpeg by drawing. The element is a text and a image. When it comes to the implementation, only image and background color is drawn but there is no text. I have no diea what happens actually even I have called canvas.drawText
The below is my code
String folderName = "droidCanvas";
String textString ="Hello , I am user 12345. \n Below is my signature.";
String fileNameString = "test.jpg";
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + folderName );
if(!folder.exists()){
folder.mkdir();
}
File bmpFile = new File(folder.getAbsolutePath() + File.separator + fileNameString );
if(!bmpFile.exists()){
try {
bmpFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//Draw something
Paint paint = new Paint();
paint.setColor(Color.RED);
Paint txtPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
txtPaint.setColor(Color.BLACK);
txtPaint.setTextSize(20);
bmpBase = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas = new Canvas(bmpBase);
canvas.drawColor(Color.WHITE);
canvas.drawCircle(w/2, h/2, 300, paint);
canvas.drawText(textString ,w/2, 0 , txtPaint);
//Export to jpeg
try
{
fos = new FileOutputStream(bmpFile);
bmpBase.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
fos = null;
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
fos.close();
fos = null;
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Try canvas.drawText(textString ,w/2, h/2 , txtPaint); and you will be able to at least see the text. Then you can re-position it later. Right now it is being drawn but you can't see it because its at extreme top center and out of bounds.
If you want to place it on top left corner then do this:
canvas.drawText(textString ,0 , txtPaint.getFontSpacing(), txtPaint);

Related

Android can't compress a recycled Bitmap

I'm getting an image from a URL, I want to compress it and save it in the external memory device. I get this error
java.lang.IllegalStateException:
Can't compress a recycled bitmap
at android.graphics.Bitmap.checkRecycled(Bitmap.java:400)
at android.graphics.Bitmap.compress(Bitmap.java:1307)
at this line
mIcon11.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
String foto = UT_drive_dropbox.AM.getfoto();
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(foto).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
final Bitmap output = Bitmap.createBitmap(mIcon11.getWidth(),
mIcon11.getHeight(), Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final int color = Color.RED;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, mIcon11.getWidth(), mIcon11.getHeight());
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(mIcon11, rect, rect, paint);
mIcon11.recycle();
String fileName = "avatar.jpg";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
mIcon11.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File sd = new File(Environment.getExternalStorageDirectory(), getString(R.string.app_name) + File.separator + fileName);
FileOutputStream fileOutputStream = null;
try {
sd.createNewFile();
fileOutputStream = new FileOutputStream(sd);
fileOutputStream.write(bytes.toByteArray());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The error message is "Can't compress a recycled bitmap". If you look three lines before your mIcon11.compress(Bitmap.CompressFormat.JPEG, 40, bytes); line, you will see:
mIcon11.recycle();
So, either get rid of recycle() or move it to after you have done everything that you intend to do with the Bitmap pointed to by mIcon11.

edittext.getdrawing cache not working.Android

I need to convert string in the edittext to bitmap, but i am not getting the string but instead i am getting this (see the image)
my code is as follows
Canvas c=new Canvas();
MainActivity.editText.setCursorVisible(false);
MainActivity.editText.buildDrawingCache();
Bitmap bmp = Bitmap.createBitmap(MainActivity.editText.getDrawingCache());
System.out.println("string is "+MainActivity.editText.getText().toString());
File f =new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Photo Text");
if(!f.exists())
{
f.mkdirs();
}
f = new File(f.getAbsolutePath(),
String.valueOf(System.currentTimeMillis()) +"phototext.jpg");
if(!f.exists())
{
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
bmp.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(f));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
c.drawBitmap(bmp,0,0, mPaint);
Please suggest me. I need the string from the edittext as a bitmap.
Why not get the text of the ExitText and then draw it on Canvas with drawText()?
String text = editText.getText().toString();
canvas.drawText(text, 0, 0, paint);
and set the canvas height and width depending of text height and length.

how to create pdf file with multiple pages from image file in android

How to create PDF file with multiple pages from image file in Android? I created one PDF file from image. That PDF file has one page. That is half of that image. In the right side search part is cut in PDF file.
I am using itext-5.3.4.jar for create PDF.
wbviewnews.loadUrl("http://developer.android.com/about/index.html");
// button for create wbpage to image than image to PDF file
Button btnclick =(Button)findViewById(R.id.btnclick);
btnclick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Picture p = wbviewnews.capturePicture();
bitmap=null;
PictureDrawable pictureDrawable = new PictureDrawable(p);
bitmap = Bitmap.createBitmap(pictureDrawable.getIntrinsicWidth(),pictureDrawable.getIntrinsicHeight(), Config.ARGB_8888);
//Bitmap bitmap = Bitmap.createBitmap(200,200, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pictureDrawable.getPicture());
ImageView imgdata=(ImageView)findViewById(R.id.imgdata);
imgdata.setImageBitmap(bitmap);
String filename = "pippo.png";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
String pdffilename = "pippo.pdf";
File pdffilepath = new File(sd, pdffilename);
try {
FileOutputStream out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
Log.e("Exception", e.toString());
}
Document document=new Document();
try {
Log.e("pdffilepath", pdffilepath.toString());
PdfWriter writer = PdfWriter.getInstance(document,new FileOutputStream(pdffilepath));
document.open();
// URL url = new URL (Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+filename);
// Log.e("url", url.toString());
Image image = Image.getInstance(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+filename) ;
document.add(image);
document.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("FileNotFoundException", e.toString());
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("DocumentException", e.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("MalformedURLException", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("IOException", e.toString());
}
}
});
Your search through StackOverflow is less I guess cause I found these answer already there having solution, yes its contained in different answer and looking at the Q/A I guess they can solve your problem, if not then keep trying :)
how to Generate Pdf File with Image in android?
How to create a PDF with multiple pages from a Graphics object with Java and itext
iText Example
if your linear layout height is very large than try this code
https://demonuts.com/android-generate-pdf-view/
follow this link and just change the lines
PdfDocument document = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, 10000, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawPaint(paint);
Bitmap bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, 10000, true);
canvas.drawBitmap(bitmap, 0, 0 , null);
document.finishPage(page);`
If you want to create a pdf file with multiple images you can use PdfDocument from Android. Here is a demo:
private void createPDFWithMultipleImage(){
File file = getOutputFile();
if (file != null){
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
PdfDocument pdfDocument = new PdfDocument();
for (int i = 0; i < images.size(); i++){
Bitmap bitmap = BitmapFactory.decodeFile(images.get(i).getPath());
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), (i + 1)).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawPaint(paint);
canvas.drawBitmap(bitmap, 0f, 0f, null);
pdfDocument.finishPage(page);
bitmap.recycle();
}
pdfDocument.writeTo(fileOutputStream);
pdfDocument.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private File getOutputFile(){
File root = new File(this.getExternalFilesDir(null),"My PDF Folder");
boolean isFolderCreated = true;
if (!root.exists()){
isFolderCreated = root.mkdir();
}
if (isFolderCreated) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "PDF_" + timeStamp;
return new File(root, imageFileName + ".pdf");
}
else {
Toast.makeText(this, "Folder is not created", Toast.LENGTH_SHORT).show();
return null;
}
}
Here images is the ArrayList of the images with path.
you can set the image like this way...
Bitmap bt=Bitmap.createScaledBitmap(btm, 200, 200, false);
bt.compress(Bitmap.CompressFormat.PNG,100, bos);

Saving Android SurfaceView to Bitmap and some elements are missing

I have my SurfaceView up and running with a button to open the camera and take a picture which is used as the background and another button to add items that sit on top and can be moved around. This all works fine until I try to save the SurfaceView as a Bitmap when all I get is the background and none of the images on top.
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if(_mGotImage){
canvas.drawBitmap(_mImage, 0, 0, null);
}else{
canvas.drawColor(Color.BLACK);
}
//if the array is not empty
if(!_mJazzItems.isEmpty()){
//step through each item in the array
for(JazzItem item: _mJazzItems){
//get the bitmap it is using
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), item.getBitmap());
//and draw that bitmap at its X and Y coords
canvas.drawBitmap(bitmap, item.getX(), item.getY(), null);
}
}
}
This is the method called to try and save the Canvas.
public void screenGrab(){
Bitmap image = Bitmap.createBitmap(_mPanelWidth, _mPanelHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
this.onDraw(canvas);
String path=Environment.getExternalStorageDirectory() + "/test2.png";
File file = new File(path);
try{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
image.compress(CompressFormat.PNG, 100, ostream);
ostream.flush();
ostream.close();
}catch (Exception e){
e.printStackTrace();
}
}
The onDraw works fine, I get my camera shot in the background and can add all my items over the top and move them around. Just when I try to get a screen shot, none of the items on top are present.
Thanks for any help!!
-- UPDATE --
I have modified the screen grab method to this:
public void screenGrab(){
Bitmap image = Bitmap.createBitmap(_mPanelWidth, _mPanelHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(image);
canvas.drawBitmap(_mImage, 0, 0, null);
//if the array is not empty
if(!_mJazzItems.isEmpty()){
//step through each item in the array
for(JazzItem item: _mJazzItems){
//get the bitmap it is using
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), item.getBitmap());
//and draw that bitmap at its X and Y coords
canvas.drawBitmap(bitmap, item.getX(), item.getY(), null);
}
}
String path=Environment.getExternalStorageDirectory() + "/test2.png";
File file = new File(path);
try{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
image.compress(CompressFormat.PNG, 100, ostream);
ostream.flush();
ostream.close();
}catch (Exception e){
e.printStackTrace();
}
}
I can't see why this is not drawing the other images over the top...
in my case i am using this:
public static Bitmap combineImages(Bitmap c, Bitmap overLayImage, Context con) {
Bitmap cs = null;
int width, height = 0;
width = c.getWidth();
height = c.getHeight();
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0, 0, null);
String left = yourleftPosition;
String top = yourtopPosition;
comboImage.drawBitmap(overLayImage, Float.parseFloat(left), Float.parseFloat(top),null);
/******
*
* Write file to SDCard
*
* ****/
String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png";
OutputStream os = null;
try {
String pathis = Environment.getExternalStorageDirectory()
+ "/DCIM/Camera/" + tmpImg;
os = new FileOutputStream(pathis);
cs.compress(CompressFormat.PNG, 100, os);
}
catch (IOException e) {
Log.e("combineImages", "problem combining images", e);
}
return cs;
}

Android save Canvas to SD

I was create image on the canvas using colorfilter
This my code
int color = mPaint.getColor();
f = new LightingColorFilter(color, 1);
mPaint.setColorFilter(f);
myBmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon10);
canvas.drawBitmap(myBmp, 20, 20, mPaint);
canvas.save();
canvas.restore();`
and then,I want to save it to sdcard
OutputStream outStream = null;
File file = new File(extStorageDirectory, "er.PNG");
try {
outStream = new FileOutputStream(file);
myBmp.compress(Bitmap.CompressFormat.PNG, 85, outStream);
outStream.flush();
outStream.close();
Toast.makeText(Draw.this, "Saved", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(Draw.this, e.toString(), Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(Draw.this, e.toString(), Toast.LENGTH_LONG).show();
}
It's Work But have Problem,My picture on sd is old picture(not filter)
can I fix this problem??,Thank
You need draw into Bitmap. Try below:
int color = mPaint.getColor();
f = new LightingColorFilter(color, 1);
mPaint.setColorFilter(f);
Bitmap outBitmap = Bitmap.Create(myBmp.getWidth(),myBmp.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(outBitmap);
canvas.drawBitmap(myBmp,20,20,mPaint);
And than you can "save it"(outBitmap) to SD card.
If you're open Bitmap with BitmapFactory you'd get immutable bitmap, and can't draw on it.
That's why you need to create temp. Bitmap, connect Canvas for draw, Drawing and can saving.

Categories

Resources