this question is easy,we can :
public static void writePhotoJpg(Bitmap data, String pathName) {
File file = new File(pathName);
try {
file.createNewFile();
// BufferedOutputStream os = new BufferedOutputStream(
// new FileOutputStream(file));
FileOutputStream os = new FileOutputStream(file);
data.compress(Bitmap.CompressFormat.JPEG, 100, os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
but this method not all successful:because "Note: not all Formats support all bitmap configs directly, so it is possible that the returned bitmap from BitmapFactory could be in a different bitdepth, and/or may have lost per-pixel alpha (e.g. JPEG only supports opaque pixels)." in the google document. without luck i have this problem: in the Camera preview i used :
private Bitmap printScreen() {
View view = this.getWindow().getDecorView();
// if (view.isDrawingCacheEnabled()) {
view.setDrawingCacheEnabled(true);
Calendar c = Calendar.getInstance();
String date = c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH) + " " + c.get(Calendar.HOUR_OF_DAY) + "-" + c.get(Calendar.MINUTE) + "-" + c.get(Calendar.SECOND);
// }
view.buildDrawingCache();
Bitmap bmp = view.getDrawingCache();
return bmp ;
}
so when i used setImageBitmap(bmp) ,looks very well,but when i open the save jpeg file it is a black jpeg.so i think the save method is not well,can you tell me another save method?
you can try this:
public static final int BUFFER_SIZE = 1024 * 8;
static void writeExternalToCache(Bitmap bitmap, File file) {
try {
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
final BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE);
bitmap.compress(CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
}
}
it works in my code, so if it's not work, try to find error:
1.the bitmap display right ?
2.where is the bitmap save file? the file has some limit? like size or ...
if the error is your post reason, you can try decode the bitmap again using Bitmap.Config.RGB_565.
Use .getRootView() method of view OR the layout contains this view, use it (e.g.) mainLayout contain one image view at index 1 then mainlayou.getChildAt(1) to get the view.
E.g.
View v1 = mainLayout.getChildAt(1); //OR View v1 = mainLayout.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
return bitmap;
Hope helpful to you...
Related
I am taking screenshot programmatically using the following code:
public static Bitmap takeScreenshot(View view)
{
try
{
// create bitmap screen capture
view.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
return bitmap;
}
catch (Throwable e)
{
CustomLogHandler.printError(e);
}
return null;
}
private static void copyFile(Bitmap bitmap)
{
File dstFile = getShareResultFile();
//Delete old file if exist.
if(dstFile.exists()) {
dstFile.delete();
}
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(dstFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, fos);
fos.flush();
}
catch (Exception e) {
CustomLogHandler.printError(e);
}
finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {
CustomLogHandler.printError(ioe);
}
}
}
}
There are several problem like:
Back arrow, title and share menu background color is not correct. It looks messy.
Background color of toolbar is totally changed.
Image quality is too poor and list items rounded drawable has not smooth corners.
Background of layout is not taken that I set as background of my parent layout.
I am taking the screenshot from the root view.
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, fos);
First, you are saving this as a JPEG. JPEG is designed for photos, and your screenshot is not a photo.
Second, you are saving this with a quality factor of 0. JPEG uses a lossy compression algorithm, and a quality factor of 0 says "please feel free to make this image be really poor, but compress it as far as you can".
I suggest switching to:
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
PNG is a better image format for a screenshot with the contents shown in your question. I don't think PNG uses the quality factor value; I put in 100 just to indicate that you want the best possible quality.
public static Bitmap takeScreenshot(View view)
{
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
This code can save view as bitmap.
But after you update your question with save code I see that you set 0 for quality, and what you expect?
#param quality Hint to the compressor, 0-100. 0 meaning compress for
* small size, 100 meaning compress for max quality. Some
* formats, like PNG which is lossless, will ignore the
* quality setting
just use your Ctrl button + click on method name to read doc about params
the answer is set second parameter 100 instead of 0!
Try using this:
public static Bitmap loadBitmapFromView(Context context, View v) {
DisplayMetrics dm = context.getResources().getDisplayMetrics();
v.measure(MeasureSpec.makeMeasureSpec(dm.widthPixels, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(dm.heightPixels, MeasureSpec.EXACTLY));
v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
Bitmap returnedBitmap = Bitmap.createBitmap(v.getMeasuredWidth(),
v.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(returnedBitmap);
v.draw(c);
return returnedBitmap;
}
and
public void takeScreen() {
Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
OutputStream fout = null;
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
fout.close();
}
}
Images are saved in the external storage folder.
try this
private void captureScreen() {
View v = this.getWindow().getDecorView().findViewById(android.R.id.content);
v.setDrawingCacheEnabled(true);
Bitmap bitmap = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File file = new File(extr, getString(R.string.free_tiket) + ".jpg");
FileOutputStream f = null;
try {
f = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, f);
f.flush();
f.close();
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "Screen", "screen");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
I have long scrollview almost 50+ fields.
I'm converting that scrollview to pdf view. pdf also creating all done.
But pdf file showing data is blur (too blur).
With some merging, I provided some reference image (I mean output image).
output image
My code:
private void takeScreenShot() {
try {
//here getScroll is my scrollview id
View u = ((Activity) mContext).findViewById(R.id.getScroll);
ScrollView z = (ScrollView) ((Activity) mContext).findViewById(R.id.getScroll);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
Bitmap bitmap = getBitmapFromView(u,totalHeight,totalWidth);
Image image;
//Save bitmap
String path = Environment.getExternalStorageDirectory()+"/Folder/";
String fileName = "report1.pdf";
File dir = new File(path);
if (!dir.exists())
dir.mkdirs();
Log.v("PDFCreator", "PDF Path: " + path);
File myPath = new File(path, fileName);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, stream);
image = Image.getInstance(stream.toByteArray());
image.setAbsolutePosition(0, 0);
Document document = new Document(image);
PdfWriter.getInstance(document, new FileOutputStream(myPath));
document.open();
document.add(image);
document.close();
} catch (Exception i1) {
i1.printStackTrace();
}
}
Any help?
Try this code:
View u = ((Activity) mContext).findViewById(R.id.getScroll);
u.setDrawingCacheEnabled(true);
u.buildDrawingCache();
Bitmap bitmap = Bitmap.createBitmap(u.getDrawingCache());
bitmap.setHasAlpha(true); //important for PNG
---------------DO SAVE WORK-----------------
v1.setDrawingCacheEnabled(false);
And at
bitmap.compress(Bitmap.CompressFormat.JPEG, 10, stream);
change 10 to 90 or 100. it is Image Quality.
Or just change in your code to higher quality.
Try another solution:
ScrollView v= (ScrollView)findViewById(R.id.getScroll);
int height = v.getChildAt(0).getHeight()
int width = v.getWidth()
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
v.layout(0, 0, v.getLayoutParams().width, v.getLayoutParams().height);
v.draw(c);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
Take a screen shot using this code and
ScrollView iv = (ScrollView) findViewById(R.id.scrollView);
Bitmap bitmap = Bitmap.createBitmap(
iv.getChildAt(0).getWidth(),
iv.getChildAt(0).getHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
c.drawColor(Color.WHITE);
iv.getChildAt(0).draw(c);
// Do whatever you want with your bitmap
saveBitmap(bitmap);
and save the bitmap as a image
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}}
I might be late but anyway. Use png format instead, increase the quality to 100 and replace
View u = ((Activity) mContext).findViewById(R.id.getScroll);
with
View u = ((Activity) mContext).findViewById(R.id.yourfirstscrollviewchild);
Thatll do the trick.
On a rooted Android device, i want to take a screenshot and convert the raw format image to a Png image then save it locally. So far, i managed to access the framebuffer, take the screenshot and save the raw image. The problem is when i convert it to Png format, the image i get is all wrong.. a bunch of white and grey lines.
Here's what i did:
public void putRawImageInArray (byte [] array, File f ) throws IOException{
#SuppressWarnings("resource")
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(f)); //The framebuffer raw image is in the file
bufferedInputStream.read(array, 0, array.length);//read the file
}
public void convertToBitmap (byte [] rawarray) throws IOException{
byte [] Bits = new byte[rawarray.length*4];
int i;
for(i=0;i<rawarray.length;i++)
{
Bits[i*4] =
Bits[i*4+1] =
Bits[i*4+2] = (byte) ~rawarray[i];
Bits[i*4+3] = -1;//0xff, that's the alpha.
}
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bm.copyPixelsFromBuffer(ByteBuffer.wrap(Bits));
File f = new File(Environment.getExternalStorageDirectory(), "/pictures/picture.png");
f.createNewFile();
if (f.exists() == true) {
f.delete();
}
try{
OutputStream fos=new FileOutputStream(f);
bm.compress(CompressFormat.PNG, 100, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
What am i doing wrong?
Try removing all this
byte [] Bits = new byte[rawarray.length*4];
int i;
for(i=0;i<rawarray.length;i++)
{
Bits[i*4] =
Bits[i*4+1] =
Bits[i*4+2] = (byte) ~rawarray[i];
Bits[i*4+3] = -1;//0xff, that's the alpha.
}
and use rawarray directly
Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
bm.copyPixelsFromBuffer(ByteBuffer.wrap(rawarray));
and make sure that the color model that you are using(Bitmap.Config.ARGB_8888) is same as the color model of the image data.
I am developing an application in which I have to take screen-shot of app screen
right now I used below code it is not working. I am null bitmap image
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/"+ "bs_score_img" +".png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
String screenShot = Environment.getExternalStorageDirectory().toString()+"/bs_score_img.png";
Log.i("TAG:Score: screenShot path=", screenShot);
Bitmap bmp = BitmapFactory.decodeFile(new File(screenShot).getAbsolutePath());
try this :
Process sh = Runtime.getRuntime().exec("su", null,null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/img.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
then read img.png as bitmap and convert it jpg as follows
Bitmap screen = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+
File.separator +"img.png");
//my code for saving
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
screen.compress(Bitmap.CompressFormat.JPEG, 15, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()+ File.separator + "test.jpg");
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();
Google has a library with which you can take screenshot without rooting, I tried that, But i am sure that it will eat out the memory as soon as possible.
Try http://code.google.com/p/android-screenshot-library/
or try this :
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.screenshots);
image.setBackgroundDrawable(bitmapDrawable);
I found this code from another post:
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + ACCUWX.IMAGE_APPEND;
// create bitmap screen capture
Bitmap bitmap;
View v1 = mCurrentUrlMask.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
imageFile = new File(mPath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Let's say that you clicked on button
findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
}
});
After that you need this two methods
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
public Bitmap screenShot(View view) {
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
just call this method with the view you want a snapshot of.. so if you want the whole screen just pass in you top most ViewGroup. if you want the System controls also just call:
you can try this
private Bitmap getScreen(){
mDecorView = getWindow().getDecorView();
runOnUiThread(new Runnable() {
public void run() {
mDecorView.invalidate();
mDecorView.post(this);
}
});
View v1 = mDecorView.getRootView();
System.out.println("Root View : "+v1);
v1.setDrawingCacheEnabled(true);
return v1.getDrawingCache();
}
here mDecorView is View .
Here how you can capture screen and save it in your storage
give permissions for creating file in external storage
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is code for activity.
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
This is how you can capture the screen.
I want to capture edit text content in image. But text can be scrollable.
How to capture with scrollable content from edit text?
without scrollable i am using the following link to do..
Create Bitmap Image from EditText & its content
Please help me to solve the issue
Here is the sample code
please try your best...
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
R.drawable.edittextimage);// get the image same as your EditText
bitmap = convertToMutable(bitmap);// converting the bitmap to mutable
Canvas cs = new Canvas(bitmap);
int h = bitmap.getHeight();
int w = bitmap.getWidth();
Paint pt = new Paint();
pt.setColor(Color.GREEN);
String iam = "your text that get from the Edit Text";
cs.drawText(iam, 0, iam.length(), (h / 2) + 10, (w / 2) / 2, pt);
pt.setColor(Color.RED);
cs.drawText("this is praki", 0, 13, h / 2, w / 3, pt);
Save_to_SD(bitmap , path)//save the bitmap in to sdcard
convertToMutable(bitmap) Methode ....
public static Bitmap convertToMutable(Bitmap imgIn) {
try {
// this is the file going to use temporally to save the bytes.
// This file will not be a image, it will store the raw image data.
File file = new File(Environment.getExternalStorageDirectory()
+ File.separator + "temp.tmp");
// Open an RandomAccessFile
// Make sure you have added uses-permission
// android:name="android.permission.WRITE_EXTERNAL_STORAGE"
// into AndroidManifest.xml file
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
// get the width and height of the source bitmap.
int width = imgIn.getWidth();
int height = imgIn.getHeight();
Bitmap.Config type = imgIn.getConfig();
// Copy the byte to the file
// Assume source bitmap loaded using options.inPreferredConfig =
// Config.ARGB_8888;
FileChannel channel = randomAccessFile.getChannel();
MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE,
0, imgIn.getRowBytes() * height);
imgIn.copyPixelsToBuffer(map);
// recycle the source bitmap, this will be no longer used.
imgIn.recycle();
System.gc();// try to force the bytes from the imgIn to be released
// Create a new bitmap to load the bitmap again. Probably the memory
// will be available.
imgIn = Bitmap.createBitmap(width, height, type);
map.position(0);
// load it back from temporary
imgIn.copyPixelsFromBuffer(map);
// close the temporary file and channel , then delete that also
channel.close();
randomAccessFile.close();
// delete the temp file
file.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return imgIn;
}
Save_to_SD(bitmap , path) methode....
public static void Save_to_SD(Bitmap bm, String image_name) {
// String extStorageDirectory =
// Environment.getExternalStorageDirectory()
// .toString();
// String meteoDirectory_path = extStorageDirectory +
// "/Weather_Belgium";
OutputStream outStream = null;
File file = new File(image_name);
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
Log.i("Hub", "OK, Image Saved to SD");
Log.i("Hub",
"height = " + bm.getHeight() + ", width = " + bm.getWidth());
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i("Hub", "FileNotFoundException: " + e.toString());
} catch (IOException e) {
e.printStackTrace();
Log.i("Hub", "IOException: " + e.toString());
}
}