I have saved a bitmap to external storage via FileOutputStream and am trying to retrieve that file in another class so that it can be put into a imageView. Here is where I save the bitmap:
public void SaveImage(Bitmap default_b) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-" + n +".png";
File file = new File (myDir, fname);
Log.i("AppInfoAdapter", "" + file);
if (file.exists()) file.delete();
try {
// File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
// + "/" + fname + ".png");
// FileOutputStream out = mContext.getApplicationContext().openFileOutput("bitmapA", Context.MODE_WORLD_WRITEABLE);
FileOutputStream out = new FileOutputStream(file);
default_b.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
and I am trying to recieve it here:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
try {
FileInputStream in = Context.openFileInput("bitmapA");
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
view.setImageBitmap(bM);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
I have done plenty of searching on this and have come across multiple ways of doing the same thing but for at the moment, this way of doing it doesn't work.
I have seen it where you use openFileOutput and openFileInput and then I have also seen where people just create new FileInput and Output streams.
Which one is better to use for the bitmap?
and then depending on which one is better to use (since I have both set up for when I save the bitmap), how can I get that bitmap from external storage?
Thanks!
Related
I use this code to save an image, but it takes a long time. Sometimes it takes 10 second or more. I have decreased the bitmap size and it helps. But it also decreases the quality. How can I save bitmap in its original size without decrease in quality and fast?
String imageName = UUID.randomUUID().toString();
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root, "/removeBG");
if (!myDir.exists()) {
myDir.mkdirs();
}
String fname;
if (imgBackground.getDrawable() != null)
fname = imageName + ".jpg";
else
fname = imageName + ".png";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile(); // if file already exists will do nothing
FileOutputStream out = new FileOutputStream(file);
bitmap = CropBitmapTransparency(bitmap);
bitmap = resizeBitmap(bitmap, MAX_SIZE, MAX_SIZE);
if (imgBackground.getDrawable() != null)
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
else
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(this, new String[]{file.toString()}, new String[]{file.getName()}, null);
I search this problem and find a soultion like this :
public static void create(OutputStream os,int cols,int rows,int r,int g,int b,int a) {
ImageInfo imi = new ImageInfo(cols, rows, 8, true); // 8 bits per channel, alpha
PngWriter png = new PngWriter(os, imi);
// just a hint to the coder to optimize compression+speed:
png.setFilterType(FilterType.FILTER_NONE);
ImageLineByte iline = new ImageLineByte (imi);
byte[] scanline = iline.getScanlineByte();// RGBA
for (int col = 0,pos=0; col < imi.cols; col++) {
scanline[pos++]=(byte) r;
scanline[pos++]=(byte) g;
scanline[pos++]=(byte) b;
scanline[pos++]=(byte) a;
}
for (int row = 0; row < png.imgInfo.rows; row++) {
png.writeRow(iline);
}
png.end();
}
I am too confused. I don't know how to use it.
MediaStore.Images.Media.insertImage (getContext ().getContentResolver (),
imgBitmap, nameFull.getText ().toString ().trim (),
"");
Try this using your own variable names. This worked for me
I am trying to store my image from imageView in bitmap, so that I can store it in the gallery of the android device. Every time I save an image, the background of the imageView is not stored. What am I missing?
Here is my code:
ImageView imageView = (ImageView) findViewById(R.id.img);
imageView.setBackgroundResource(R.drawable.img1);
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();
Code to store the image into the gallery is:
FileOutputStream outStream = null;
File dir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyAlbum");
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.d("MyAlbum", "failed to create directory");
Toast.makeText(MainActivity.this, "Failed to make directory", Toast.LENGTH_SHORT).show();
}
}
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(getApplicationContext(), "PICTURE SAVED", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(dir));
sendBroadcast(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can take a screenshot of this view (ImageView) in this case, it will simply take what's drawn on this view at this moment and turn it into a bitmap you can save.
Answer is mentioned here already.
The magical part is that
ImageView yourImageView = .. // Get reference it to your view.
yourImageView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(yourImageView.getDrawingCache());
yourImageView.setDrawingCacheEnabled(false);
Ta-da you can use your snapshot btimap.
you can try this out,
private void saveImageToStorage(Bitmap finalBitmap, String image_name) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root);
myDir.mkdirs();
String fname = "Image-" + image_name+ ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
Log.i("LOAD", root + fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Happy coding :-)
I create take a screenshot in Android through a button click, but image can't be saved. I have an error message in "No such file or directory". What can I do?
My code:
public class MainActivity extends Activity {
LinearLayout L1;
ImageView image;
Bitmap bm;
File file;
FileOutputStream fileoutputstream;
View v1;
ByteArrayOutputStream bytearrayoutputstream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bytearrayoutputstream = new ByteArrayOutputStream();
L1 = (LinearLayout) findViewById(R.id.layout);
Button but = (Button) findViewById(R.id.Button01);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try
{
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
final ScrollView scrollview = (ScrollView) findViewById(R.id.scroll);
scrollview.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener(){
#Override
public void onScrollChanged() {
if (scrollview != null) {
if (scrollview.getChildAt(0).getBottom() <= (scrollview.getHeight() + scrollview.getScrollY())) {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try
{
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
} else {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView01);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("bottom-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
// String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try
{
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
});
}
}
Image can't be saved in sdcard. What mistake did I make? I can't understand what is the problem or how to save an image on sdcard?
I use this method to capture screen. 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);
}
Try this,
Before write the file you have to check the permissions for marshmallow
public static final int REQUEST_STORAGE = 101;
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST_STORAGE);
} else {
writeFile()
}
}
/*check permissions for marshmallow*/
#SuppressWarnings("BooleanMethodIsAlwaysInverted")
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
/*get Permissions Result*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("TAG", "PERMISSION_GRANTED");
writeFile();
} else {
Toast.makeText(mContext, "The app was not allowed to write to your storage", Toast.LENGTH_LONG).show();
}
}
}
}
public void writeFile()
{
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try
{
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
final String root = Environment.getExternalStorageState().toString();
File myDir=new File(root + "/saved_images/" );
State is no storage. Change to:
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images" );
And adapt your code for mkdirs as explained in comment.
if (!myDir.exists())
{
if (!myDir.mkdirs())
{
Toast.makeText(this, "Sorry could not create directory:\n" + myDir.getAbsolutePath(), Toast.LENGTH_LONG).show();
return;
}
}
You complain that the file is not created but it starts with the directory.
You never answered my question about Androud version. But for 6.0 and above you should ask the user also for runtime permission. Add that code.
Or, as a quick solution, go to the Android settings of your app and switch the Storage toggle button to ON.
I have a FileOutputstream here:
public void SaveImage(Bitmap default_b) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-" + n +".jpg";
File file = new File (myDir, fname);
if (file.exists()) file.delete();
try {
FileOutputStream out = openFileOutput("file", Context.MODE_WORLD_WRITEABLE);
default_b.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
But I get an error on this line:
FileOutputStream out = openFileOutput("file", Context.MODE_WORLD_WRITEABLE);
Saying that openFileOutput is undefined *(please note that this is in a base adapter class, and when I try to do it from context, Context.getApplicationContext().openFileOutput gets the error that "Cannot make a static reference to the non-static method getApplicationContext() from type Context") I also get the warning that Context.MODE_WORLD_WRITABLE is deprecated.
Then I have my FileInputstream here (in another class that extends BaseAdapter):
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(mContextGV);
Log.d("GridViewAdapter", "new imageView added");
}
try {
FileInputStream in = new openFileInput("file");
BufferedInputStream buf = new BufferedInputStream(in);
byte[] bitMapA = new byte[buf.available()];
buf.read(bitMapA);
Bitmap bM = BitmapFactory.decodeByteArray(bitMapA, 0, bitMapA.length);
view.setImageBitmap(bM);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
e.printStackTrace();
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
That has an error on this line:
FileInputStream in = new openFileInput("file");
saying that openFileInput is undefined and once again when I change it to:
FileInputStream in = new Context.getApplicationContext().openFileInput("file");
I get an error saying that "Context.getApplicationContext() cannot be resolved to a type"
Try to Replace File OutputStream Code
String fname = "Image-" + n ;
File file = new File (myDir, fname);
if (file.exists()) file.delete();
try {
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/" + fname +".png");
FileOutputStream fos = new FileOutputStream(f);
default_b.compress(Bitmap.CompressFormat.PNG,90,fos);
} catch (Exception e) {
e.printStackTrace();
}
its works perfect For me to Save Image
i want to create a bitmap of whats being currently displayed of my app, one thing i went into is cant read FB buffer requires root, would like to know if it is possible to create a image file for the screen, please i want the help to code this, no 3rd party intents , thanks, answers would be much appreciated
From your Activity (pseudo-code):
Bitmap bm = Bitmap.create...
Canvas canvas = new Canvas(bm);
getWindow.getDecorView().draw(canvas);
You can use FFMPEG to capture the Screen
Try this.....
{
LinearLayout view = (LinearLayout) findViewById(R.id.imageLayout);
View v1 = view.getRootView();
v1.setDrawingCacheEnabled(true);
String dir="myimages";
Bitmap bm = v1.getDrawingCache();
saveBitmap(bm, dir, "capturedimage");
}
static String saveBitmap(Bitmap bitmap, String dir, String baseName) {
try {
File sdcard = Environment.getExternalStorageDirectory();
File pictureDir = new File(sdcard, dir);
pictureDir.mkdirs();
File f = null;
for (int i = 1; i < 200; ++i) {
String name = baseName + i + ".png";
f = new File(pictureDir, name);
if (!f.exists()) {
break;
}
}
System.out.println("Image size : "+bitmap.getHeight());
if (!f.exists()) {
String name = f.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(name);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
System.out.println("After File Size : "+f.length());
fos.flush();
fos.close();
return name;
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception in saveBitmap: "+e.getMessage());
} finally {
}
return null;
}