Download/save viewing picture from application resource - android

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

Related

Share loaded image with glide from imageview

I have a loaded image on my imageview widget which was loaded from glide library. I want to use a share intent to share that image to other applications. I have tried various possibilities without any success. Please help.
public class BookstorePreviewActivity extends AppCompatActivity {
ImageView imageView;
LinearLayout mShare;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookstore_preview);
imageView = findViewById(R.id.image_preview_books);
mShare= findViewById(R.id.download_books);
mShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// fetching image view item from cache
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath());
try {
cachePath.createNewFile();
FileOutputStream outputStream = new FileOutputStream(cachePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
// sharing image to other applications (image not found)
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(cachePath));
startActivity(Intent.createChooser(share, "Share via"));
}
});
Just Pass activity context to the takeScreenShot activity it will
work!!!
public 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;
//Find the screen dimensions to create bitmap in the same size.
DisplayMetrics dm = activity.getResources().getDisplayMetrics();
int width = dm.widthPixels;
int height = dm.heightPixels;
Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
takeScreen(b,activity);
return b;
}
public static void takeScreen(Bitmap bitmap,Activity a) {
//Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
String mPath = Environment.getExternalStorageDirectory() + File.separator + "tarunkonda" + System.currentTimeMillis() + ".jpeg";
File imageFile = new File(mPath);
try {
OutputStream fout = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
openScreenshot(imageFile,a);
}
private static void openScreenshot(File imageFile,Activity activity) {
Intent intent = new Intent(activity,ImageDrawActivity.class);
intent.putExtra(ScreenShotActivity.PATH_INTENT_KEY,imageFile.getAbsolutePath());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(intent);
}

get imageview from viewpager to save and share from button

I have a list of images from picasa. I put it in grid view and then on click have the fullscreen image that is done by viewpager. I tried many ways to get bitmap or get imageview from view pager adapter but it is giving null. Please help me, I'm new, this is my first app and I'm confused.
This is my code :
package com.example.soha.livingroom;
public class fullimafepager extends Activity implements OnClickListener {
// TouchImageView imgflag;
// BitmapDrawable btmpDr;
private static final String STATE_POSITION = "STATE_POSITION";
// #InjectView(R.id.pager)
LruBitmapCache lreucach;
private PrefManager prefmanger;
private List<String> images = new ArrayList<String>();
private String imageuri;
// Picasa JSON response node keys
// Declare Variables
private ViewPager viewPager;
private ImageAdapter adapter;
private int npostion;
// private Bitmap[] image2;
private int position;
// private im selectedPhoto;
private LinearLayout llSetWallpaper, llDownloadWallpaper;
private Utils utils;
private ProgressBar pbLoader;
private View view;
private Bitmap bitmap;
private ImageView fullImageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from viewpager_main.xml
prefmanger = new PrefManager(getApplicationContext());
setContentView(R.layout.viewpager_main);
if (getIntent().getExtras() != null) {
this.images = getIntent().getExtras().getStringArrayList("list");
position = getIntent().getIntExtra("postion", 0);
;
// fullImageView= images.get(position);
Log.d("=======", "Data " + images.get(1));
Toast.makeText(this, "the" + images.get(1) + position, Toast.LENGTH_LONG).show();
// Intent i = getIntent();
// image selectedPhoto = (image) getIntent().getSerializableExtra(TAG_SEL_IMAGE);
// System.out.println(images);
}
prefmanger = new PrefManager(getApplicationContext());
// Generate sample data
// flag = new int[] { R.drawable.ico_loader, R.drawable.ico_loader, R.drawable.ico_loader, R.drawable.ico_loader};
// Locate the ViewPager in viewpager_main.xml
viewPager = (ViewPager) findViewById(R.id.pager);
// Pass results to ViewPagerAdapter Class
adapter = new ImageAdapter(fullimafepager.this, images);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
// viewPager.setCurrentItem(0);
viewPager.setCurrentItem(position);
Log.d("test", "Current Page:"+viewPager.getCurrentItem());
// fullImageView= (ImageView) viewPager.getChildAt(position);
npostion= viewPager.getCurrentItem();
// fullImageView= (TouchImageView) viewPager.findViewById(R.id.imgFullscreen);
fullImageView= (TouchImageView) viewPager.findViewWithTag("pos" + viewPager.getCurrentItem());
Log.d("test", "Current uri:" + fullImageView);
// Log.d("test", "Current Page:"+npostion);
// view = fullimafepager.viewPager.getChildAt(fullimafepager.viewPager.getCurrentItem()).getRootView();
// fullImageView = (ImageView)fullimafepager.viewPager.findViewWithTag("myview" + fullimafepager.viewPager.getCurrentItem());
// Log.d("=======", "Data " + fullImageView);
//addition
// imageUri = images.get(npostion);
// uri = Uri.parse(imageUri);
// imageuri=images.get(npostion);
// bitmap=lreucach.getBitmap(imageuri);
llSetWallpaper = (LinearLayout) findViewById(R.id.llSetWallpaper);
llDownloadWallpaper = (LinearLayout) findViewById(R.id.llDownloadWallpaper);
pbLoader = (ProgressBar) findViewById(R.id.pbLoader);
// hide the action bar in fullscreen mode
// fullImageView = (ImageView) findViewById(R.id.imgFullscreen);
// getActionBar().hide();
// utils = new Utils(getApplicationContext());
// layout click listeners
llSetWallpaper.setOnClickListener(this);
llDownloadWallpaper.setOnClickListener(this);
// setting layout buttons alpha/opacity
llSetWallpaper.getBackground().setAlpha(70);
llDownloadWallpaper.getBackground().setAlpha(70);
}
#Override
public void onClick(View v) {
Bitmap bitmap = ((BitmapDrawable) fullImageView.getDrawable())
.getBitmap();
// Bitmap bitmap = ((BitmapDrawable) imgflag.getBitmap();
/* Bitmap bitmap1= null;
try {
bitmap1 = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(imageuri));
} catch (IOException e) {
e.printStackTrace();
}*/
Log.d("test", "Current uri:" + bitmap);
switch (v.getId()) {
case R.id.llDownloadWallpaper:
// utils.saveImageToSDCard(bitmap);
{ File myDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
prefmanger.getGalleryName());
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Wallpaper-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(
fullimafepager.this,
fullimafepager.this.getString(R.string.toast_saved).replace("#",
"\"" + prefmanger.getGalleryName() + "\""),
Toast.LENGTH_SHORT).show();
// Log.d(this, "Wallpaper saved to: " + file.getAbsolutePath());
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(fullimafepager.this,
fullimafepager.this.getString(R.string.toast_saved_failed),
Toast.LENGTH_SHORT).show();}}
break;
// button Set As Wallpaper tapped
case R.id.llSetWallpaper:
// utils.shareIt(bitmap);
{ /*Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
// share.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));*/
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, "title");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
Uri uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
OutputStream outstream;
try {
outstream = getContentResolver().openOutputStream(uri);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outstream);
outstream.close();
} catch (Exception e) {
System.err.println(e.toString());
}
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share, "Share Image"));
}
break;
default:
break;
}
}
/**
* #author Terry E-mail: yaoxinghuo at 126 dot com
* #version create: 2010-10-21 ??01:40:03
*/
}
and this is my adapter
public class ImageAdapter extends PagerAdapter {
private Activity _activity;
// Declare Variables
Context context;
Utils utiles;
TouchImageView imgflag;
LruBitmapCache lreucach;
private List<String> image2;
private LayoutInflater inflater;
private Bitmap bitmap;
//new
private image selectedPhoto;
public ImageAdapter(Activity activity,
List<String> flag) {
this._activity = activity;
this.image2 = flag;
}
#Override
public int getCount() {
return this.image2.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((TouchImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int postion) {
// Declare Variables
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.activity_fullscreen_image, container,
false);
imgflag = (TouchImageView) itemView.findViewById(R.id.imgFullscreen);
// fullImageView.setOnTouchListener(this);
// Capture position and set to the ImageView
Picasso.with(_activity).load(image2.get(postion)).into(imgflag);
imgflag.setTag("pos" + postion);
// imgflag.setImageURI(Uri.parse("http:/i.dailymail.co.uk/i/pix/2014/0‌​9/27/1411832985119_Puff_Image_galleryImage_SUNDERLAND_ENGLAND_SEPTEM.JPG"));
/* Uri imgUri = Uri.parse(image2.get(postion));
imgflag.setImageURI(null);
imgflag.setImageURI(imgUri);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(image2.get(postion), options);
imgflag.setImageBitmap(bitmap);*/
// bitmap = ((BitmapDrawable) imgflag.getDrawable()).getBitmap();;
// Bitmap bitmap;
// OutputStream output;
// utiles.setBitmap();
// Add viewpager_item.xml to ViewPager
((ViewPager) container).addView(imgflag);
// lreucach.putBitmap(image2.get(postion),bitmap);
Log.d("test", "Adapter creating item:" + postion);
return imgflag;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// Remove viewpager_item.xml from ViewPager
((ViewPager) container).removeView((TouchImageView) object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
public Bitmap getBtmap(){
BitmapDrawable btmpDr = (BitmapDrawable) imgflag.getDrawable();
bitmap = btmpDr.getBitmap();
return bitmap;
}

Save two images as a single image in android

I have an image view in android and on that image view i have another image view.. Both image views contain two different images.. Now i want to save it as a single JPG image in my phone gallery.. So how can i do that??
I tried some code but it is not working.
Here is my code.
XML File:
<ImageView
android:id="#+id/innerImage"
android:layout_width="300dp"
android:layout_height="230dp"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:contentDescription="#android:string/untitled"
android:background="#drawable/white"/>
<Button
android:id="#+id/btnselectPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/ivImage"
android:layout_alignLeft="#+id/ivImage"
android:layout_marginBottom="16dp"
android:text="#string/select_photo" />
<ImageView
android:id="#+id/ivImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:contentDescription="#android:string/untitled" />
<Button
android:id="#+id/btnsave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/btnselectPhoto"
android:layout_alignBottom="#id/btnselectPhoto"
android:layout_alignRight="#+id/ivImage"
android:layout_marginLeft="32dp"
android:layout_toRightOf="#id/btnselectPhoto"
android:text="#string/save" />
And here is my Java Code:
public class MainActivity extends ActionBarActivity {
private static String mTempDir;
Bitmap mBackImage, mTopImage, mBackground, mNewSaving;
Canvas mComboImage;
FileOutputStream mFileOutputStream;
BitmapDrawable mBitmapDrawable;
private String mCurrent = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call method for selecting Image
SelectImage();
}
// method for selecting image
private void SelectImage() {
// items to put in alert box
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
// Alert box
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo");
// Click Event of button
Button btn = (Button) findViewById(R.id.btnselectPhoto);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Set items in alert box
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// Start Camara
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
// Open Gallery
else if (items[item].equals("Choose from Library")) {
Intent intent = new Itent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, 2);
}
// Cancel code
else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
});
}
// This method is called for setting image in imageview.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final String picturePath;
ImageView iv = (ImageView) findViewById(R.id.innerImage);
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
// bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
iv.setImageBitmap(bm);
String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
f.delete();
OutputStream fOut = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
// Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
saveimage(picturePath);
}
}
}
private void saveimage(String imgPath) {
mTempDir = Environment.getExternalStorageDirectory() + "/" + "Demo" + "/";
File mTempFile = new File(mTempDir);
if (!mTempFile.exists()) {
mTempFile.mkdirs();
}
mCurrent = "temp.png";
mBackground = Bitmap.createBitmap(604, 1024, Bitmap.Config.ARGB_8888);
mBackImage = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
mTopImage = BitmapFactory.decodeFile(imgPath);
mComboImage = new Canvas(mBackground);
mComboImage.drawBitmap(mBackImage, 0f, 0f, null);
mComboImage.drawBitmap(mTopImage, 0f, 0f, null);
Button savebtn = (Button) findViewById(R.id.btnsave);
savebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
mBitmapDrawable = new BitmapDrawable(getResources(), mBackground);
mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
String FtoSave = mTempDir + mCurrent;
File mFile = new File(FtoSave);
mFileOutputStream = new FileOutputStream(mFile);
mNewSaving.compress(CompressFormat.PNG, 95, mFileOutputStream);
mFileOutputStream.flush();
mFileOutputStream.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
I worked on a similar issue once, and i solved it by putting both images in the same linear layout an creating Bitmap from that layout. Than you can just write a function to save that Bitmap where ever you want.
Here's some sample code:
private Bitmap getBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Toast.makeText(StopWarApp.getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
public void combineImages(Bitmap c, Bitmap s,String loc) {
Bitmap cs = null;
int width, height = 0;
if(c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, 0f, c.getHeight(), null);
String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png";
OutputStream os = null;
try {
os = new FileOutputStream(loc + tmpImg);
cs.compress(CompressFormat.PNG, 100, os);
} catch(IOException e) {
Log.e("combineImages", "problem combining images", e);
}
}
You can combine two bitmaps using this.
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
ll=(LinearLayout)findViewById(R.id.linearlayout);
//Add button in your layout and write the below code onclick of button.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ll.setDrawingCacheEnabled(true);
Bitmap bitmap = ll.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/saved_picture");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = n + ".jpg";
File file = new File(newDir, fotoname);
String s = file.getAbsolutePath();
System.err.print("Path of saved image." + s);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
});

How to save images from imageView to SD

I save a picture from imageView to SD. The image is saved.
The problem is that there is the first image, and saving the next image again saved the first with a different name.
As I understand need to catch the moment when the picture from imageView is loaded into playImage. But how to do it?
Thank's.
Load the image in imageView and save to sd:
public class Gallery extends Activity implements OnClickListener {
String item;
Button btnsave, btnhome;
ImageView playImage;
String fotoname;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
btnhome = (Button) findViewById(R.id.btn_home);
btnhome.setOnClickListener(this);
btnsave = (Button)findViewById(R.id.btn_save);
btnsave.setOnClickListener(this);
playImage = (ImageView)findViewById(R.id.displayImage);
final ImageView playImage = (ImageView) findViewById(R.id.displayImage);
final LinearLayout myGallery = (LinearLayout) findViewById(R.id.mygallery1);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
item = extras.getString("item");
if(item.equals("Item")){
try {
String galleryDirectoryName = "ITEM/item";
String[] listImages = getAssets().list(galleryDirectoryName);
for (String imageName : listImages) {
InputStream is = getAssets().open(galleryDirectoryName + "/" + imageName);
final Bitmap bitmap = BitmapFactory.decodeStream(is);
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new ViewGroup.LayoutParams(350, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bitmap);
imageView.setPadding(10, 70, 10, 70);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playImage.setImageBitmap(bitmap);
playImage.setPadding(5, 0, 5, 0);
}
});
myGallery.addView(imageView);
}
} catch (IOException e) {
Log.e("GalleryWithHorizontalScrollView", e.getMessage(), e);
}
}
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btn_save:
playImage.setDrawingCacheEnabled(true);
Bitmap bitmap = playImage.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/." + (getString(R.string.app_name)));
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Toast.makeText(this, (getString(R.string.saved)), Toast.LENGTH_SHORT ).show();
} catch (Exception e) {
}
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(newDir, fotoname);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
break;
case R.id.btn_home:
finish();
}
}
}
Check this.
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ll.setDrawingCacheEnabled(true);
Bitmap bitmap = ll.getDrawingCache();
// bitmap = Bitmap.createBitmap(480, 800,
// Bitmap.Config.ARGB_8888);
String root = Environment.getExternalStorageDirectory()
.toString();
File newDir = new File(root + "/Collage_Maker");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "cm_"+n + ".jpg";
File file = new File(newDir, fotoname);
String s = file.getAbsolutePath();
Log.i("Path of saved image.", s);
System.err.print("Path of saved image." + s);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
Toast.makeText(getApplicationContext(), "Photo Saved "+ fotoname,
Toast.LENGTH_SHORT).show();
out.close();
} catch (Exception e) {
Log.e("Exception", e.toString());
}
}
});

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.

Categories

Resources