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..
Related
I am programming a simple drawing application with drawLines:
public void onDraw(Canvas canvas) {
setBackgroundColor(cfgBackground); //background
//canvas.drawColor(ConfigActivity.getCfgBackground(ConfigActivity.cfgBackground)); //to keep background when export to PNG/JPG
//title
paint.setColor(0xbb020a0d);
paint.setTextSize(40);
canvas.drawText(Title, 0, 40, paint);
paint.setColor(color);
paint.setStrokeWidth(thickness);
canvas.drawLines(lines, paint);
}
This is no problem. When export the screen to image file, the image shows normal in the preview screen (with all other photos in the phone), but when open this image, it shows darken, as following:
I have tried Method A/B/C like following, but the result not much different:
File sdCard = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File file = new File(sdCard, imageName);
FileOutputStream fos = null;
try {
// Make sure the Pictures directory exists.
sdCard.mkdirs();
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
Toast.makeText(getContext(), file + " open failed: " + e, Toast.LENGTH_SHORT).show();
e.printStackTrace();
return;
}
/* //method A: will get dark image
setDrawingCacheEnabled(true);
Bitmap b = getDrawingCache();
//b.setHasAlpha(true); //to set transparency
//Canvas canvas = new Canvas(b);
//canvas.drawColor(cfgBackground)); //trying to solve darken image
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
setDrawingCacheEnabled(false); //for next screen update
*/
Bitmap b = screenShot(this); //Method B
b.compress(Bitmap.CompressFormat.PNG, 100, fos);
try {
fos.flush();
fos.close();
} catch (IOException e) {
Toast.makeText(getContext(), file + " save failed: " + e, Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
Toast.makeText(getContext(), file + " saved in Albums", Toast.LENGTH_SHORT).show();
//add to gallary
getContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.toString())));
Two functions:
//Method C
public static Bitmap getBitmapFromView(View view) {
//Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
//Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
//Get the view's background
Drawable bgDrawable =view.getBackground();
if (bgDrawable!=null)
//has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
//does not have background drawable, then draw white background on the canvas
canvas.drawColor(cfgBackground);
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
//Method B
public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
Anyone encountered this problem?
I finally found the solution (although not sure why): the background color should be 0xFFrrggbb, eg. 0xffeeee00, though the background looks ugly but just needs more finetune...
If you know why, kindly share here, appreciated!
How to get the bitmap of current layout(For sharing the screen as image) instead of taking screenshot? I'm getting the view of layout using following line,
I can able to get bitmap of this layout but the image is looking as empty(I got blank image). This is my code.
View cardShareView = getLayoutInflater().inflate(R.layout.activity_cad_profile, null);
boolean imageResult=saveImageInLocal(getBitmapFromView(cardShareView), "cad_share.png") == true
public static Bitmap getBitmapFromView(View view) {
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.draw(canvas);
return bitmap;
}
private boolean saveImageInLocal(Bitmap imageData, String filename) {
String iconsStoragePath = Environment.getExternalStorageDirectory() + "/KKMC/";
File sdIconStorageDir = new File(iconsStoragePath);
//create storage directories, if they don't exist
sdIconStorageDir.mkdirs();
try {
filePath = sdIconStorageDir.toString() + filename;
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
//choose another format if PNG doesn't suit you
imageData.compress(Bitmap.CompressFormat.PNG, 70, bos);
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
} catch (IOException e) {
Log.w("TAG", "Error saving image file: " + e.getMessage());
return false;
}
return true;
}
Advance Thanks for your response.
Expecting this image
Bit I got this image
Finally, I created duplicate layout(activity_cad_profile.xml) for take the full view as image which is loaded at the time of main layout is loading. I don't know this is correct way or not. But it's working fine for me.
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
I am using this API demo of the Developer site, THIS DEMO.
But i am wonder that how to save that image in to My Andrtoid Device.
Is please anyone give the Code to save that drawn image to the Android Device.
Thanks.
try this code
View content = your_view;
content.setDrawingCacheEnabled(true);
content.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
Bitmap bitmap = content.getDrawingCache();
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
File file = new File(path+"/image.png");
FileOutputStream ostream;
try {
file.createNewFile();
ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.flush();
ostream.close();
Toast.makeText(getApplicationContext(), "image saved", 5000).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "error", 5000).show();
}
drawView.setDrawingCacheEnabled(true);
Bitmap bm = null;
drawView.destroyDrawingCache();
bm=drawView.getDrawingCache();
Then write the bitmap to file using bitmap factory.
One option is create another Canvas (as shown below) and repeat all your drawing on this new canvas.
Once done, call drawBitmap.
Bitmap bitmap = new Bitmap(// Set the params you like //);
Canvas canvas = new Canvas(bitmap);
// Do all your drawings here
canvas.drawBitmap(// The first picture //);
The best would be if there was a way to copy an existing canvas and then you wont need to re-draw everything but I couldn't find one.
I have implemented the below approach & worked for me.
Get your CustomView by using its id from xml file but not by instantiating the Customview.
View v = findViewById(R.id.custom_view);
//don't get customview by this way, View v = new CustomView(this);
int canvasWidth = v.getWidth();
int canvasHeight = v.getHeight();
Bitmap bitmap = Bitmap.createBitmap(canvasWidth, canvasHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
v.draw(canvas);
ImageView imageView = findViewById(R.id.image_view);
imageView.setImageBitmap(bitmap);
All code should be inside saveButton click listener.
I am Using the Function to Mearge the Two Bitmap File on One Another and it also overlay.
I am using this Function to Overlay it on OneAnother.
public static Bitmap combineImages(Bitmap cameraImage, Bitmap visionImage) { // can add a 3rd parameter 'String loc' if you want to save the new image - left some code to do that at the bottom
Bitmap finalImage = null;
int width, height = 0;
width = cameraImage.getWidth();
height = cameraImage.getHeight();
finalImage = Bitmap.createBitmap(width, height, cameraImage.getConfig());
Canvas canvas = new Canvas(finalImage);
canvas.drawBitmap(cameraImage, new Matrix(), null);
canvas.drawBitmap(visionImage, new Matrix(), null);
// this is an extra bit I added, just incase you want to save the new image somewhere and then return the location
/*String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png";
OutputStream os = null;
try {
os = new FileOutputStream(loc + tmpImg);
finalImage.compress(CompressFormat.PNG, 100, os);
} catch(IOException e) {
Log.e("combineImages", "problem combining images", e);
}*/
return finalImage;
}
But After saving this Image I show that images to be combine with each other. it is not overlay. I want it to be Overlay on One Another.
Please tell me where i am wrong in this Function ??
Thanks.
this is the function to overlay two bitmap,s
private Bitmap overlayMark(Bitmap bmp1, Bitmap bmp2) {
int bh = originalBitmap.getHeight();
int bw = originalBitmap.getWidth();
Bitmap bmOverlay = Bitmap.createBitmap(bw,bh,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, 0, 0, null);
canvas.drawBitmap(bmp2, 0,0, null);
return bmOverlay;
}