I'm trying to save my view as an image. I have done some work, doesn't show any error but I can find the location where is the image saved(or in the gallery). Is the image created at all, or I'm having some other issues? The image should be saved when pressing red from options menu:
case R.id.red:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String FILENAME="Boenka";
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parent.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap( parent.getWidth(), parent.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
parent.draw(canvas);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
return true;
This is my main - Draw class
public class Draw extends Activity {
DrawView drawView;
SignatureView signature;
private RelativeLayout parent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
parent = (RelativeLayout) findViewById(R.id.signImageParent);
signature = new SignatureView(getApplicationContext(), null);
signature.setColor(Color.MAGENTA);
parent.addView(signature);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_options_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.clear:
signature.clear();
return true;
case R.id.red:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String FILENAME="Boenka";
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
parent.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap( parent.getWidth(), parent.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
parent.draw(canvas);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
return true;
case R.id.blue:
signature.setColor(Color.BLUE);
return true;
case R.id.yellow:
signature.setColor(Color.YELLOW);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onBackPressed() {
this.finish();
super.onBackPressed();
}
}
public void saveImage(Bitmap b,int count) throws Exception
{
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
String s=at.getText().toString();
String alphaAndDigits = s.replaceAll("[^a-zA-Z0-9]+","_");
String fileName = alphaAndDigits+"_"+wr.name+"_"+count;
File file = new File(path, fileName+".jpg");
newFile=Uri.fromFile(file);
uris.add(newFile);
fOut = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
Try this function it worked well for me, this is for saving the bitmap please ensure that drawing cache is working fine for you.
Try below code, it works
Add below permission in manifest
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MainActivity.java
public class MainActivity extends Activity implements OnClickListener{
private DrawableView drawableView; //here I have taken customview, it is optional, I am saving this view as image. You can take any layout or view
private Button saveBtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
drawableView = (DrawableView) findViewById(R.id.drawable_view);
saveBtn = (Button) findViewById(R.id.save_btn);
saveBtn.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.save_btn:
File file = saveBitMap(this, drawableView); //which view you want to pass that view as parameter
if (file != null) {
Log.i("TAG", "Drawing saved to the gallery!");
} else {
Log.i("TAG", "Oops! Image could not be saved.");
}
break;
default:
break;
}
private File saveBitMap(Context context, View drawView){
File pictureFileDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"Handcare");
if (!pictureFileDir.exists()) {
boolean isDirectoryCreated = pictureFileDir.mkdirs();
if(!isDirectoryCreated)
Log.i("ATG", "Can't create directory to save the image");
return null;
}
String filename = pictureFileDir.getPath() +File.separator+ System.currentTimeMillis()+".jpg";
File pictureFile = new File(filename);
Bitmap bitmap =getBitmapFromView(drawView);
try {
pictureFile.createNewFile();
FileOutputStream oStream = new FileOutputStream(pictureFile);
bitmap.compress(CompressFormat.PNG, 100, oStream);
oStream.flush();
oStream.close();
} catch (IOException e) {
e.printStackTrace();
Log.i("TAG", "There was an issue saving the image.");
}
scanGallery(pictureFile.getAbsolutePath(), context);
return pictureFile;
}
//create bitmap from view and returns it
private 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(Color.WHITE);
}
// draw the view on the canvas
view.draw(canvas);
//return the bitmap
return returnedBitmap;
}
// used for scanning gallery
private void scanGallery(Context cntx, String path) {
try {
MediaScannerConnection.scanFile(cntx, new String[] { path },null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
I want to take current activity screenshot and share it on share item click in actionbar share button. When I run application nothing would be shown me as a output. How can I take current screen screenshot? please tell me the proper sequence of it.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item:
try{
takeScreenShot(av); // av is instance of hello
}
catch (Exception e) {
System.out.println(e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public static void shoot(Activity a,String b) {
//savePic(takeScreenShot(a), "sdcard/xx.png");
savePic(takeScreenShot(a), b);
}
private static Bitmap takeScreenShot(Activity activity)
{
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay().getHeight();
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return b;
}
private static void savePic(Bitmap b, String strFileName)
{
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(strFileName);
if (null != fos)
{
b.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.flush();
fos.close();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Here is the code that allowed my screenshot to be stored on sd card and used later for whatever your needs are:
First, add proper permission to save file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code (running in an 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();
}
}
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
check this answer https://stackoverflow.com/a/5651242/4342876
I have a question.
I try to save canvas image to file
here is how i work.
1.Create canvas object with bitmap(form image)
2.print Text on canvas (Using drawText)
3.save with bitmap.compress() method
but it saved only original bitmap(with out text)
I wonder how I can save text printed bitmap to file?
Here is my code
protected class MyView extends View{
public MyView(Context context){
super(context);
}
public void onDraw(Canvas canvas){
Paint pnt = new Paint();
pnt.setColor(Color.BLACK);
canvas.scale(0.5f,0.5f);
Resources res = getResources();
BitmapDrawable bd =(BitmapDrawable)res.getDrawable(R.drawable.hanhwa);
Bitmap bit = bd.getBitmap();
canvas.drawBitmap(bit,0,0,null);
pnt.setTextSize(30);
canvas.drawText("hello",290,340,pnt);
canvas.restore();
//file save//
File folder = new File(Environment.getExternalStorageDirectory()+"/DCIM/tmp");
boolean isExist = true;
if(!folder.exists()){
isExist = folder.mkdir();
}
if(isExist){
File file = null;
boolean isFileExist = false ;
file = new File(folder.getPath() + "/tmp.jpg");
if(file != null && !file.exists()){
try{
isFileExist = file.createNewFile();
} catch(IOException e){
e.printStackTrace();
}
}
else{
}
if(file.exists()){
FileOutputStream fos = null;
try{
fos = new FileOutputStream(file);
bit.compress(Bitmap.CompressFormat.JPEG,100,fos);
}
catch(Exception e){
e.printStackTrace();
}
finally{
try{
fos.close();
}
catch(IOException e){
e.printStackTrace();
}
}
}
}
else{
//Toast.makeText(MyView.this,"foler not exist.",Toast.LENGTH_LONG).show();
}
}
}
Bitmap.compresss()
this method write a compressed version of the bitmap to the specified outputstream.
Pass bitmap instance to canvas
Here is the pseudo-code.
(except other statement, ex. try-catch, statement)
Canvas c = new Canvas(bit);
c.drawText("hello",290,340,pnt);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
this post will be helpful too.
My code is as follow :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button upload = (Button) findViewById(R.id.screeshotdButton);
upload.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
folderCheck();
}
});
}
private void folderCheck(){
File folder = new File(Environment.getExternalStorageDirectory() + "/cloze_screenshots");
boolean success = true;
// If the folder cloze not exist, create one
if (!folder.exists()) {
success = folder.mkdir();
}else{
ScreenShot();
}
// If mkdir successful
if (success) {
ScreenShot();
} else {
Log.e("mkdir_fail","QQ");
}
}
private void ScreenShot(){
String filePath = Environment.getExternalStorageDirectory()+ "/cloze_screenshots/temp.png";
// create bitmap screen capture
Bitmap bitmap;
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
OutputStream fout = null;
File imageFile = new File(filePath);
try {
fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
Toast.makeText(this, "Success", Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This code can take a fullscreen screenshot , but I want to take a screenshot on specific area (For example, the left block on the screen ) programmatically after I press the button.
Any code or suggestion will be appreciate.
You can wrap the contents in a layout for example LinearLayout and follow the above code for taking screenshot by using the methods on the wrapped layout.
Bitmap bitmap;
ViewGroup v1 = findViewById(R.id.layout_id);
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
Below method takes snapshot of given view which is adjustable by means of height and width then returns bitmap of it
public static Bitmap takeSnapshot(View givenView, int width, int height) {
Bitmap bm = Bitmap.createBitmap(width , height, Bitmap.Config.ARGB_8888);
Canvas snap = new Canvas(bm);
givenView.layout(0, 0, givenView.getLayoutParams().width, givenView.getLayoutParams().height);
givenView.draw(snap);
return bm; }
Hi In my application I am making an application in android in which I have to take screenshot of current activity and save it into sdcard.
For that i used one menu button named as download if i click the download i want to save the current activity into sdcard.
Now My problem is it's saving into sdcard but screenshot coming half.I want to download the whole screen and save it into sdcard.how to download the full activity.
Can anyone please help me how to solve this problem.
notify_image
public class notify_image extends Activity {
ImageView imageView;
Activity av=notify_image.this;
Bitmap b;
String strFileName;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_image);
imageView = (ImageView) findViewById(R.id.iv_imageview);
Intent in = getIntent();
String title = in.getStringExtra("TAG_TITLE");
String url = in.getStringExtra("TAG_URL");
String name = in.getStringExtra("TAG_NAME");
String place = in.getStringExtra("TAG_PLACE");
String date = in.getStringExtra("TAG_DATE");
final String URL =url;
TextView stitle = (TextView) findViewById(R.id.tv_title);
TextView sname = (TextView) findViewById(R.id.tv_name);
TextView splace = (TextView) findViewById(R.id.tv_place);
TextView sdate = (TextView) findViewById(R.id.tv_date);
// displaying selected product name
stitle.setText(title);
sname.setText(name);
splace.setText(place);
sdate.setText(date);
// Create an object for subclass of AsyncTask
GetXMLTask task = new GetXMLTask();
// Execute the task
task.execute(new String[] { URL });
}
//creating button
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.downloads, menu);
return true;
}
//button on click function
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.downloads:
/*Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
*/
//captureScreen(v);
try{
Bitmap bitmap = takeScreenShot(av); // av is instance of hello
savePic(bitmap, strFileName);
}
catch (Exception e) {
System.out.println(e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay()
.getHeight();
// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return b;
}
/*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();
}
}*/
#SuppressWarnings("unused")
private static void savePic(Bitmap bitmap, String strFileName) {
//File strFileName1 = new File(Environment.getExternalStorageDirectory() + "/screenshottt.png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream("mnt/sdcard/print.png");
if (null != fos) {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
System.out.println("b is:"+bitmap);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void shoot(Activity a,String b) {
//savePic(takeScreenShot(a), "sdcard/xx.png");
savePic(takeScreenShot(a), b);
}
/*public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}*/
/*public Bitmap captureScreen(View v)
{
Bitmap bitmap = null;
try {
if(v!=null)
{
int width = v.getWidth();
int height = v.getHeight();
Bitmap screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
v.draw(new Canvas(screenshot));
}
} catch (Exception e)
{
Log.d("captureScreen", "Failed");
}
return bitmap;
}
*/
/* 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;
}*/
/* 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);
}
}*/
//image url convert to bitmap
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
Thanks In Advance.
new updated code
public class notify_image extends Activity {
ImageView imageView;
Activity av=notify_image.this;
Bitmap b;
String strFileName;
Button download;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_image);
imageView = (ImageView) findViewById(R.id.iv_imageview);
download = (Button) findViewById(R.id.button1);
download();
Intent in = getIntent();
String title = in.getStringExtra("TAG_TITLE");
String url = in.getStringExtra("TAG_URL");
String name = in.getStringExtra("TAG_NAME");
String place = in.getStringExtra("TAG_PLACE");
String date = in.getStringExtra("TAG_DATE");
final String URL =url;
TextView stitle = (TextView) findViewById(R.id.tv_title);
TextView sname = (TextView) findViewById(R.id.tv_name);
TextView splace = (TextView) findViewById(R.id.tv_place);
TextView sdate = (TextView) findViewById(R.id.tv_date);
// displaying selected product name
stitle.setText(title);
sname.setText(name);
splace.setText(place);
sdate.setText(date);
// Create an object for subclass of AsyncTask
GetXMLTask task = new GetXMLTask();
// Execute the task
task.execute(new String[] { URL });
}
//creating button
/* public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.downloads, menu);
return true;
}
*/
//button on click function
/* public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.downloads:
Bitmap bitmap = takeScreenshot();
saveBitmap(bitmap);
//captureScreen(v);
try{
Bitmap bitmap = takeScreenShot(av); // av is instance of hello
savePic(bitmap, strFileName);
}
catch (Exception e) {
System.out.println(e);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}*/
private void download() {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
/*Intent nextScreen = new Intent(getApplicationContext(), KnowYourLeader.class);
startActivity(nextScreen);*/
try{
Bitmap bitmap = takeScreenShot(av); // av is instance of hello
savePic(bitmap, strFileName);
}
catch (Exception e) {
System.out.println(e);
}
}
private static Bitmap takeScreenShot(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b1 = view.getDrawingCache();
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;
int width = activity.getWindowManager().getDefaultDisplay().getWidth();
int height = activity.getWindowManager().getDefaultDisplay()
.getHeight();
// Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
- statusBarHeight);
view.destroyDrawingCache();
return b;
}
/*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();
}
}*/
#SuppressWarnings("unused")
private static void savePic(Bitmap bitmap, String strFileName) {
//File strFileName1 = new File(Environment.getExternalStorageDirectory() + "/screenshottt.png");
FileOutputStream fos = null;
try {
fos = new FileOutputStream("mnt/sdcard/print.png");
if (null != fos) {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
System.out.println("b is:"+bitmap);
fos.flush();
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void shoot(Activity a,String b) {
//savePic(takeScreenShot(a), "sdcard/xx.png");
savePic(takeScreenShot(a), b);
}
/*public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}*/
/*public Bitmap captureScreen(View v)
{
Bitmap bitmap = null;
try {
if(v!=null)
{
int width = v.getWidth();
int height = v.getHeight();
Bitmap screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
v.draw(new Canvas(screenshot));
}
} catch (Exception e)
{
Log.d("captureScreen", "Failed");
}
return bitmap;
}
*/
/* 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;
}*/
/* 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);
}
}*/
//image url convert to bitmap
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
}
Here is the code that allowed my screen shot to be stored on sd card and used later for whatever your needs are, you can achieve it with following 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 = view.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();
}
Then, when you need to access use something like this:
Uri uri = Uri.fromFile(new File(mPath));
Try out below code to capture the whole screen and save as bitmap.:
View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, "print.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage( getContentResolver(), b,
"Screen", "screen");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Hope this will help you.
I use below code to convert, but it seems can only get the content in the display screen and can not get the content not in the display screen.
Is there a way to get all the content even out of scroll?
Bitmap viewBitmap = Bitmap.createBitmap(mScrollView.getWidth(),mScrollView.getHeight(),Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(viewBitmap);
mScrollView.draw(canvas);
We can convert all the contents of a scrollView to a bitmap image using the code shown below
private void takeScreenShot()
{
View u = ((Activity) mContext).findViewById(R.id.scroll);
HorizontalScrollView z = (HorizontalScrollView) ((Activity) mContext).findViewById(R.id.scroll);
int totalHeight = z.getChildAt(0).getHeight();
int totalWidth = z.getChildAt(0).getWidth();
Bitmap b = getBitmapFromView(u,totalHeight,totalWidth);
//Save bitmap
String extr = Environment.getExternalStorageDirectory()+"/Folder/";
String fileName = "report.jpg";
File myPath = new File(extr, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myPath);
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(mContext.getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
Bitmap returnedBitmap = Bitmap.createBitmap(totalWidth,totalHeight , Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(returnedBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
view.draw(canvas);
return returnedBitmap;
}
The Pops answer is really good, but in some case you could have to create a really big bitmap which could trigger a OutOfMemoryException when you create the bitmap.
So I made a little optimization to be gently with the memory :)
public static Bitmap getBitmapFromView(View view, int totalHeight, int totalWidth) {
int height = Math.min(MAX_HEIGHT, totalHeight);
float percent = height / (float)totalHeight;
Bitmap canvasBitmap = Bitmap.createBitmap((int)(totalWidth*percent),(int)(totalHeight*percent), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(canvasBitmap);
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
bgDrawable.draw(canvas);
else
canvas.drawColor(Color.WHITE);
canvas.save();
canvas.scale(percent, percent);
view.draw(canvas);
canvas.restore();
return canvasBitmap;
}
This one works for me
To save the bitmap check runtime permission first
#OnClick(R.id.donload_arrow)
public void DownloadBitMap()
{
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
{
downloadData();
Log.e("callPhone: ", "permission" );
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
Toast.makeText(this, "need permission", Toast.LENGTH_SHORT).show();
}
}
To get bitmap
private void downloadData() {
ScrollView iv = (ScrollView) findViewById(R.id.scrollView);
Bitmap bitmap = Bitmap.createBitmap(
iv.getChildAt(0).getWidth()*2,
iv.getChildAt(0).getHeight()*2,
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bitmap);
c.scale(2.0f, 2.0f);
c.drawColor(getResources().getColor(R.color.colorPrimary));
iv.getChildAt(0).draw(c);
// Do whatever you want with your bitmap
saveBitmap(bitmap);
}
To save the bitmap
public void saveBitmap(Bitmap bitmap) {
File folder = new File(Environment.getExternalStorageDirectory() +
File.separator + "SidduInvoices");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Do something on success
} else {
// Do something else on failure
}
File imagePath = new File(Environment.getExternalStorageDirectory() + "/SidduInvoices/Siddus.png");
if(imagePath.exists())
{
imagePath=new File(Environment.getExternalStorageDirectory() + "/SidduInvoices/Siddus"+custamername.getText().toString()+".png");
}
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
progressBar.cancel();
final File finalImagePath = imagePath;
new SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
.setTitleText("Saved")
.setContentText("Do you want to share this with whatsapp")
.setCancelText("No,cancel !")
.setConfirmText("Yes,share it!")
.showCancelButton(true)
.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sweetAlertDialog) {
sweetAlertDialog.cancel();
shareImage(finalImagePath);
}
})
.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
#Override
public void onClick(SweetAlertDialog sDialog) {
sDialog.cancel();
}
})
.show();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
You need get the total width and height of the scrollview, or you created viewBitmap is too small to contain the full content of the scrollview.
check this link
Android: Total height of ScrollView
The issue here is that the only actual pixel content that ever exists is that which is visible on the display screen. Android and other mobile platforms are very careful about memory use and one of the ways a scrolling view can maintain performance is to not draw anything that is offscreen. So there is no "full" bitmap anywhere -- the memory containing the content that moves offscreen is recycled.