for taking screen shot i have am using below code
public void takeScreenShot(){
File wallpaperDirectory = new File("/sdcard/Hello Kitty/");
if(!wallpaperDirectory.isDirectory()) {
// have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
// create a File object for the output file
}
File outputFile = new File(wallpaperDirectory, "Hello_Kitty.png");
// now attach the OutputStream to the file object, instead of a String representation
// create bitmap screen capture
Bitmap bitmap;
View v1 = mDragLayer.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache(),0,0,v1.getWidth(),v1.getHeight());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
try {
fout = new FileOutputStream(outputFile);
// Bitmap bitMap = Bitmap.createBitmap(src)
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();
}
}
and now i want a cropped bitmap in that i want to crop some portion from left and some portion from bottom so i have used code like this
Bitmap.createBitmap(v1.getDrawingCache(),v1.getWidth()/10,v1.getHeight()/10,v1.getWidth(),v1.getHeight());
but i got an error
08-29 23:41:49.819: E/AndroidRuntime(3486): java.lang.IllegalArgumentException: x + width must be <= bitmap.width()
08-29 23:41:49.819: E/AndroidRuntime(3486): at android.graphics.Bitmap.createBitmap(Bitmap.java:410)
08-29 23:41:49.819: E/AndroidRuntime(3486): at android.graphics.Bitmap.createBitmap(Bitmap.java:383)
can anybody tell me how to crop portion of an bitmap from left and bottom thanks...
It appears you misunderstood the usage of that specific Bitmap.create(...) function. Rather than supplying the source's width and height as the last two parameters, you should specificy the width and height the cropped result should end up with.
The error explains that since you specified an offset from the left and top, but passed in the source's dimensions, the cropped result would exceed the bounds of the original image.
If all you want to do is crop a tenth off the left and top, simply subtract the offsets from the original width/height:
Bitmap source = v1.getDrawingCache();
int x = v1.getWidth()/10;
int y = v1.getHeight()/10
int width = source.getWidth() - x;
int height = source.getHeight() - y;
Bitmap.createBitmap(source, x, y, width, height);
Instead of using
Bitmap.createBitmap(v1.getDrawingCache(),v1.getWidth()/10,v1.getHeight()/10,v1.getWidth(),v1.getHeight());
You can use bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Refer here for some more methods Bitmap
Related
i M passing a bitmap from one activity to other, after taking the screen shot
Bitmap bitmap;
bitmap = takeScreenshot();
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bitmap.recycle();
//Pop intent
Intent in1 = new Intent(this, FinalImageShare.class);
in1.putExtra("image", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
here i am getting the image in other activity , the problem is that the tool bar height is also coming (i m hiding the toool bar by setVisibility, )i want to crop the image so that toolbar height wont come.TIA
imageView=(ImageView)findViewById(R.id.imageView);
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
You can use createBitmap method, like so:
resizedbitmap = Bitmap.createBitmap(bitmap, 0, 0, yourwidth, yourheight);
Where bitmap is the bitmap you create, and resizedbitmap is the cropped one.
createBitmap() method takes as parameter in this case: bitmap, start X, start Y, width and height.
You can use those two methods to get your width and height:
bitmap.getWidth(), bitmap.getHeight()
Check also this link to learn about the createBitmap method:
Developer site
Or you can use the drawing cache property for this, like this :
View main = findViewById(R.id.view);
Bitmap screenshot;
main.setDrawingCacheEnabled(true);
screenshot = Bitmap.createBitmap(main.getDrawingCache());
main.setDrawingCacheEnabled(false);
Or similar to the last one, ctx.getWindow().getDecorView() View to get full screen bitmap cache:
View view = ctx.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
Bitmap bmap = view.getDrawingCache();
int contentViewTop = ctx.getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop(); /* skip status bar in screenshot */
Storage.shareBitmapInfo = Bitmap.createBitmap(bmap, 0, contentViewTop, bmap.getWidth(), bmap.getHeight() - contentViewTop, null, true);
view.setDrawingCacheEnabled(false);
Hope this helps!
I have a LinearLayout and I am want to save the contents of that view as an image. I have it half working.
File imageFile;
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/a.png";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
Bitmap bitmap;
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.PNG, 10, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
With the above code it will save a copy of the view, but only what's seen on the device screen. I have more information on the view that I want saved. The code above from here and this will only save the information seen on the screen as an image. I want all the information saved, even the information that is not on the screen (where you need to scroll to see).
How can I achieve that?
Another option is to use:
Bitmap b = Bitmap.createBitmap(width, height....)
v1.setLayoutParams // Full width and height of content
Canvas c = new Canvas(b);
v1.draw(c); // You now have full bitmap
saveBitmap(b);
Run a measure/layout pass on it and draw it to a canvas. Suppose your parent was called "view" and was a vertical LinearLayout:
view.measure(someWidth, MeasureSpec.UNSPECIFIED);
Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.draw(c);
I need take screenshot of entire screen in Android, I've searched a lot but they all talked about taking screenshot of specified view, how can I take screenshot of entire screen?
I mean, by program.(Not by DDMS)
There is a library available for taking snapshot through the device its called ASL(Android Screenshot library).
Have a look here with complete source code
In eclipse go to DDMS perspective and select your device. Then click on screen capture(camera picture) button.
Go through this link it may be helpful for you...
Try below code:
// 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();
}
Refer to this answer.
You need to root your device otherwise it won't work. Also u have to make ur application get SuperUser access. Just implement this code and you will be good to go:
public void screenShot() throws InterruptedException
{
Process sh;
try
{
sh = Runtime.getRuntime().exec("su", null, null);
OutputStream os = sh.getOutputStream();
os.write(("/system/bin/screencap -p " + "/sdcard/Image.png").getBytes("ASCII"));
os.flush();
os.close();
sh.waitFor();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This code return screenshot of visible and unvisible part of layout.
private Bitmap getScreenBitmap() {
View v = getWindow().getDecorView().findViewById(android.R.id.content);
v.setDrawingCacheEnabled(true);
int measureSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
v.measure(measureSpec, measureSpec);
width = v.getMeasuredWidth();
height = v.getMeasuredHeight();
v.layout(0, 0, width, height);
v.buildDrawingCache(true);
//Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
Bitmap b = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(b);
v.draw(canvas);
v.setDrawingCacheEnabled(false);
return b;
}
In Eclipse go to Window -> Show View -> Other -> Devices
Select your device and then simply click on "camera picture":
I changed my question a bit.
EDIT:
// make textures from text
public static void createTextureFromText(GL10 gl, String text, String texName) {
Paint p = new Paint();
p.setColor(Color.GREEN);
p.setTextSize(32 * getResources().getDisplayMetrics().density);
// get width and height the text takes (in px)
int width = (int) p.measureText(text);
int height = (int) p.descent();
// Create an empty, mutable bitmap based on textsize
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
// get a canvas to paint over the bitmap
Canvas canvas = new Canvas(bmp);
bmp.eraseColor(Color.CYAN); //Cyan for debugging purposes
//draw the text
canvas.drawText(text, 0, 0, p);
// save image - for debugging purposes
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
// create a new file name "test.jpg" in sdcard
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.jpg");
try {
f.createNewFile();
// write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
.... make texture
}
I now have this code in use for creating textures from given text (this is just partially).
But I found the fault lies somewhere in the Bitmap creation. I now save the Bitmap on the sd-card, to see how it turns out and found I get a ALL Cyan bitmap (672B, 164x7 are the dimensions).
Does Anyone see why it doesn't create an Bitmap with text on it? What can I be doing wrong?
You'll be a hero if you could help me :)
Firstly, your text height calculation is wrong. The 'descent' measurement is just the portion of text below the baseline (i.e. the tails of 'g' and 'q' etc). The correct height is ascent+descent, except that since ascent is negative you want:
int height = (int) (p.descent() + -p.ascent());
Secondly, when you drawText() the y coordinate you give it is where the baseline goes, it is not the top or bottom edge. So if you want to fill a bitmap that's just big enough to hold the text, your y coordinate should also be -p.ascent().
I'm developing an application for taking screenshots in the device. In this application, we can draw anything on the screen. For this I am using Canvas, Paint and Path to do this.
I'm using this code to take screenshots:
public void saveScreenshot()
{
if (ensureSDCardAccess())
{
Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
onDraw(canvas);
File file = new File(mScreenshotPath + "/" + System.currentTimeMillis() + ".jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.e("Panel", "FileNotFoundException", e);
} catch (IOException e) {
Log.e("Panel", "IOEception", e);
}
}
}
/**
* Helper method to ensure that the given path exists.
* TODO: check external storage state
*/
private boolean ensureSDCardAccess() {
File file = new File(mScreenshotPath);
if (file.exists()) {
return true;
} else if (file.mkdirs()) {
return true;
}
return false;
}
However, when the following line is run:
Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
my application closes with the following exception:
11-28 15:05:46.291: E/AndroidRuntime(8209): java.lang.IllegalArgumentException: width and height must be > 0
If I change the height and width, the screenshot is taken, but it's empty:
Why is that happening? What am I doing wrong?
You can do it like this,
Give the id for your main Layout & after you display the content on the screen write the below code on some Listener say button click or menu item or any such Listener(make sure you call these line after your layout is display else it will give a blank screen).
View content = findViewById(R.id.myLayout);
content.setDrawingCacheEnabled(true);
getScreen(content);
method getScreen(content)
private void getScreen(View content)
{
Bitmap bitmap = content.getDrawingCache();
File file = new File("/sdcard/test.png");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Also don't for to add permission for writing file to SDCard.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
Exception is because the height and width of Bitmap you are creating is zero
try below code to get height and width
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
In case there is no access to getWindowManager
Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
getWidth(), getHeight() required to be called with context, if your are trying it outside Activity it will fail. Try getApplicationContext.getWidth().
Could you show more of your code pls? It seems like you are calling width and height have not positive integer values. You could debug this by printing the values of width and height.
I faced a similar issue and the solution was:
You get width and heigh before your view is drown so check first if width or heigh equal zero:
if (getWidth() == 0 || getHeight() == 0) {
initRemote(remote);
isViewInitialized=false;
}
isViewInitialized is a member value.
Then put this code in OnSizeChanged
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if(!isViewInitialized&&){
// this is the right place to take snapshot :)
}
}
I have wrapped the screenshot code into a very simple library. It allows you to take screenshots and store them to the disk if you want.
https://github.com/abdallahalaraby/Blink