How to save images correctly to sd-card? - android

I'm an android beginner with little knowledge of coding. I've implemented a save button in my viewfippler gallery but I'm getting two errors on this line " Bitmap bitmap = getBitmapFromImageView(ImageView imageView);" in the saveimage() method. The compiler is saying there's a ")" expected and there's an illegal start of expression on the line specified above. The relevant code is below.
ViewFlipper.java
public class ViewFlipperActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btnSave).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
saveimage();
}
});
........
}
public Bitmap getBitmapFromImageView(ImageView imageView) {
int viewWidth = imageView.getWidth();
int viewHeight = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
imageView.layout(0, 0, viewWidth, viewHeight);
imageView.draw(canvas);
return bitmap;
}
public static void saveimage(){
Bitmap bitmap = getBitmapFromImageView(ImageView imageView);
File f =new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/HD GOSPEL LOCKSCREENS");
if(!f.exists())
{
f.mkdirs();
}
f = new File(f.getAbsolutePath(),
String.valueOf(System.currentTimeMillis()) +"hdgospelLockScreen.jpg");
if(!f.exists())
{
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(f));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
.......
}

Your syntax is incorrect. Change this line: Bitmap bitmap = getBitmapFromImageView(ImageView imageView); to Bitmap bitmap = getBitmapFromImageView(imageView); where imageView is an ImageView object.
EDIT: Also, your static function saveImage should take in the ImageView object:
public static void saveImage(ImageView imageView) {

Related

Android : taking Screenshot of the selected area programmatically

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; }

current activity taking screenshot and save image into sdcard in android

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.

Download/save viewing picture from application resource

How do I set my application to download/save to phone the image I am previewing?
I Tried with the code below but it's not working, it gives me error and I can't figure out where is that error. So what am I supposed to replace and with what?
public class FullImageActivity extends Activity {
Bitmap bm;
boolean isSDAvail=false, isSDWriteable = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.full_image);
//AdView ad = (AdView) findViewById(R.id.adView);
//ad.loadAd(new AdRequest());
// get intent data
Intent i = getIntent();
// Selected image id
final int position = i.getExtras().getInt("id");
final ImageAdapter imageAdapter = new ImageAdapter(this);
final ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.mThumbIds[position]);
checkSDstuff();
}
private void checkSDstuff() {
// TODO Auto-generated method stub
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)){
//write
isSDAvail = true;
isSDWriteable =true;
}else if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
//read only
isSDAvail =true;
isSDWriteable = false;
}else{
//uh oh
isSDAvail = false;
isSDWriteable =false;
}
Button buttonSave = (Button)findViewById(R.id.download);
buttonSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(isSDAvail && isSDWriteable){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String name = filename.getText().toString(); //how to set name from postion
File file = new File(path, name + ".jpeg");
path.mkdirs();
InputStream is = getResources().openRawResource(R.drawable.pic); //here to set (imageAdapter.mThumbIds[position]) from position of ImageView
OutputStream os = new FileOutputStream(file);
byte[] data = new byte[is.available()];
is.read(data);
os.write(data);
is.close();
os.close();
}
}
});
}
Here is code to create a bitmap from an ImageView:
public Bitmap getBitmapFromImageView(ImageView imageView) {
int viewWidth = imageView.getWidth();
int viewHeight = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
imageView.layout(0, 0, viewWidth, viewHeight);
imageView.draw(canvas);
return bitmap;
}
Then to save the Bitmap:
try {
Bitmap bmp = getBitmapFromImageView(imageView);
FileOutputStream out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}

how to overlay one bitmap to another and save on sdcard

i am developing image editor and im using custom class to draw bitmap, here is my code..
private void settingBitmapToDraw() {
// TODO Auto-generated method stub
resultBitmap=Bitmap.createScaledBitmap(resultBitmap, WIDTH, HEIGHT, true);
Matrix matrix=new Matrix();
matrix.setRotate(TO_DEGREE);
tempBitmap=Bitmap.createBitmap(resultBitmap, 0, 0, WIDTH, HEIGHT,
matrix, true);
bitmap=Bitmap.createBitmap(WIDTH, HEIGHT, tempBitmap.getConfig());
canvas=new Canvas(bitmap);
invalidate();
}
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawBitmap(tempBitmap, xAxis, yAxis, paint);
if(overlayBitmap!=null)
{
canvas.drawBitmap(overlayBitmap, xAxis+50, yAxis+50, paint);
}
}
public void overlayImage() {
// TODO Auto-generated method stub
ImageProcessing.SAVE_STATUS=false;
overlayBitmap=BitmapFactory.decodeResource(getResources(),
R.drawable.add_image);
invalidate();
}
The bitmap is drawn on canvas but while saving it saves as a black image.
this is my save bitmap code...
try {
FileOutputStream fos=new FileOutputStream(file);
updatedBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
SAVE_STATUS=true;
saveDialog.dismiss();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
updated bitmap is initialized by 'bitmap'
public Bitmap getUpdatedImage() {
// TODO Auto-generated method stub
//width=2048 height=1232
Bitmap updatedBitmap=Bitmap.createScaledBitmap(bitmap,
orgWidth, orgHeight, true);
return updatedBitmap;
}
//////////////
my ImageProcessing.java class has code...
if(!SAVE_STATUS)
{
updatedBitmap=ip_DrawingClass.getUpdatedImage();
if(updatedBitmap!=null)
{
file=new File(file_root);
saveDialog.show();
}
else
{
Toast.makeText(ImageProcessing.this,
"file can't saved...", Toast.LENGTH_SHORT).show();
}
}
and saveDialog has save button which holds code for saving image written above.
///////////////////////////
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
float xAxis,yAxis;
switch(event.getAction()&MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
MODE="DRAG";
startX=event.getX();
startY=event.getY();
if(ImageProcessing.drawLineStatus)
path.moveTo(startX, startY);
break;
case MotionEvent.ACTION_POINTER_DOWN:
MODE="ZOOM";
oldDist=this.findDistanceXY(event);
break;
case MotionEvent.ACTION_MOVE:
if(MODE=="ZOOM")
{
newDist=findDistanceXY(event);
if(newDist>oldDist)
{
this.applyZooming("plus");
}
else
{
this.applyZooming("minus");
}
oldDist=newDist;
}
else if(MODE=="DRAG")
{
xAxis=event.getX();
yAxis=event.getY();
if(!lock_status)
{
this.translateImage(xAxis,yAxis,startX,startY);
}
else
{
this.translateTextOnBitmap
(xAxis,yAxis,startX,startY);
}
if(ImageProcessing.drawLineStatus)
{
path.lineTo(xAxis, yAxis);
this.drawLinesOnBitmap();
}
else
draw_line=false;
}
break;
case MotionEvent.ACTION_POINTER_UP:
MODE="DRAG";
this.setZoomBoxXY();
break;
case MotionEvent.ACTION_UP:
this.set_XY_Axis();
break;
}
return true;
}
image translate here..
public void translateImage(float x, float y, float startX, float startY) {
// TODO Auto-generated method stub
if((startX>=imageAtX&&startX<=(imageAtX+imageW))&&
(startY>=imageAtY&&startY<=(imageAtY+imageH)))
{
if(imagePortionSelected||crop_status)
{
if((startX>=selectorAtX&&startX<=(selectorAtX+ZOOM))
&&(startY>=selectorAtY&&startY<=(selectorAtY+ZOOM)))
{
left=(int)(x-(startX-selectorAtX));
top=(int)(y-(startY-selectorAtY));
right=left+ZOOM;
bottom=top+ZOOM;
checkForValidityOfPara();
}
rect.set(left, top, right, bottom);
}
else
{
xAxis=x-(startX-imageAtX);
yAxis=y-(startY-imageAtY);
}
}
invalidate();
}
For combining 2 bitmaps use below method
public Bitmap combineImages(Bitmap frame, Bitmap image) {
Bitmap cs = null;
Bitmap rs = null;
rs = Bitmap.createScaledBitmap(frame, image.getWidth(),
image.getHeight(), true);
cs = Bitmap.createBitmap(rs.getWidth(), rs.getHeight(),
Bitmap.Config.RGB_565);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(image, 0, 0, null);
comboImage.drawBitmap(rs, 0, 0, null);
if (rs != null) {
rs.recycle();
rs = null;
}
Runtime.getRuntime().gc();
return cs;
}
And for saving combined Image use below code wherever you want...
Bitmap outBmp = combineImages(bmp1, bmp2);
imageFileFolder = new File(Environment.getExternalStorageDirectory(),
"FOLDER_PHOTOS");
imageFileFolder.mkdir();
FileOutputStream out1 = null;
imageFileName = new File(imageFileFolder, "file_name.jpg");
out1 = new FileOutputStream(imageFileName);
outBmp.compress(Bitmap.CompressFormat.JPEG, 100, out1);
out1.flush();
out1.close();
Use this code. you have to save your drawing layout as the image. hope below code will help you.
Bitmap bm;
DrawingLayout.setDrawingCacheEnabled(true);
bm = DrawingLayout.getDrawingCache();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
//String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/drawn_image";
String path = getFilesDir() .getAbsolutePath();
boolean exists = (new File(path)).exists();
/*if (!exists) {
new File(path).mkdirs();
}*/
OutputStream outStream = null;
File file = new File(path, "drawn_image" + ".PNG");
try {
outStream = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You are not drawing on the updated bitmap. Draw the first bitmap and the overlay bitmap on the updated one before saving it. Change your getUpdatedImage() to this-
protected void getUpdatedImage() {
int width = tempBitmap.getWidth();
int height = tempBitmap.getHeight();
Bitmap updatedBitmap=Bitmap.createScaledBitmap(bitmap,
width, height, true);
Canvas canvas = new Canvas(updatedBitmap);
canvas.drawBitmap(tempBitmap, xAxis, yAxis, paint);
if(overlayBitmap!=null)
{
canvas.drawBitmap(overlayBitmap, xAxis+50, yAxis+50, paint);
}
//now save the updated bitmap
return updatedBitmap;
}
to save bitmap try this...-
public void savebitmap(final Bitmap bitmap)
{
AlertDialog.Builder alert = new AlertDialog.Builder(Work.this);
alert.setMessage("File name :"); //get file name from user
input = new EditText(Work.this);
input.setLayoutParams(new LayoutParams(100,50));
alert.setView(input);
alert.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String _mNameValue = input.getText().toString();
try
{
File fn=new File("/sdcard/"+_mNameValue+".png");
FileOutputStream out=new FileOutputStream(fn);
Toast.makeText(getApplicationContext(), "In Save",Toast.LENGTH_SHORT).show();
bitmap.compress(Bitmap.CompressFormat.PNG, 90,out);
out.flush();
out.close();
Toast.makeText(getApplicationContext(), "File is Saved in "+fn, Toast.LENGTH_SHORT).show();
}
catch(Exception e){
e.printStackTrace();
}
}
});
alert.show();
}
this is working perfectly at my place.
ontouch event-
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(getResources().getColor(R.color.Yellow)) ;
paint.setAlpha(opacity);
_ImageView.setAdjustViewBounds(true);
_ImageView.setImageBitmap(_MutableImage1);
canvas1 = new Canvas(_MutableImage1);
canvas1.drawRect(event.getX()-10,event.getY()-10,event.getX()+10,event.getY()+10, paint);
bitmap1=_MutableImage1.copy(Bitmap.Config.ARGB_4444,false);

How to convert all content in a scrollview to a bitmap?

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.

Categories

Resources