How to save a bitmap on internal storage
Asked Answered
H

6

50

this is my code I and I want to save this bitmap on my internal storage. The public boolean saveImageToInternalStorage is a code from google but I don't know how to use it. when I touch button2 follow the button1 action.

public class MainActivity extends Activity implements OnClickListener {
Button btn, btn1;
SurfaceView sv;
Bitmap bitmap;
Canvas canvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn=(Button)findViewById(R.id.button1);
    btn1=(Button)findViewById(R.id.button2);
    sv=(SurfaceView)findViewById(R.id.surfaceView1);

    btn.setOnClickListener(this);
    btn1.setOnClickListener(this);

    bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

}
@Override
public void onClick(View v) {
    canvas=sv.getHolder().lockCanvas();
    if(canvas==null) return;
    canvas.drawBitmap(bitmap, 100, 100, null);
    sv.getHolder().unlockCanvasAndPost(canvas);


}

public boolean saveImageToInternalStorage(Bitmap image) {

    try {
    // Use the compress method on the Bitmap object to write image to
    // the OutputStream
    FileOutputStream fos = openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);

    // Writing the bitmap to the output stream
    image.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.close();

    return true;
    } catch (Exception e) {
    Log.e("saveToInternalStorage()", e.getMessage());
    return false;
    }
    }
 }
Homo answered 27/3, 2013 at 15:8 Comment(0)
M
121

To Save your bitmap in sdcard use the following code

Store Image

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    } 
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

To Get the Path for Image Storage

/** Create a File for saving an image or video */
private  File getOutputMediaFile(){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files"); 

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    } 
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
} 

EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.

public onClick(View v){

switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
} 
}
Myrtamyrtaceous answered 27/3, 2013 at 15:14 Comment(5)
capturedImage and mImageName how must be created?Homo
thank you so much, but the button2 still follow the button1 fucntionHomo
i like to use JPEG : Bitmap.CompressFormat.JPEGPelorus
I don't know why this is the accepted answer because the question is about internal storage and this answer is about external storage...Torticollis
Question is about internal storage :(Replica
R
13
private static void SaveImage(Bitmap finalBitmap) {

    String root = Environment.getExternalStorageDirectory().getAbsolutePath();
    File myDir = new File(root + "/saved_images");
    myDir.mkdirs();

    String fname = "Image-"+ o +".jpg";
    File file = new File (myDir, fname);
    if (file.exists ()) file.delete ();
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}
Register answered 23/12, 2016 at 23:55 Comment(0)
E
1

Modify onClick() as follows:

@Override
public void onClick(View v) {
    if(v == btn) {
        canvas=sv.getHolder().lockCanvas();
        if(canvas!=null) {
            canvas.drawBitmap(bitmap, 100, 100, null);
            sv.getHolder().unlockCanvasAndPost(canvas);
        }
    } else if(v == btn1) {
        saveBitmapToInternalStorage(bitmap);
    }
}

There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.

I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:

if(v == btn) {
    ...
    btn1.setEnabled(true);
}
Exedra answered 27/3, 2013 at 15:13 Comment(2)
how must to be view from if(view == btn) and else if(view == btn1)?Homo
I edited "view" -> "v". These two if() statements determine which button was pressed inside your onClick() function.Exedra
H
1

To save file into directory

  public static Uri saveImageToInternalStorage(Context mContext, Bitmap bitmap){

    String mTimeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());

    String mImageName = "snap_"+mTimeStamp+".jpg";

    ContextWrapper wrapper = new ContextWrapper(mContext);

    File file = wrapper.getDir("Images",MODE_PRIVATE);

    file = new File(file, "snap_"+ mImageName+".jpg");

    try{

        OutputStream stream = null;

        stream = new FileOutputStream(file);

        bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);

        stream.flush();

        stream.close();

    }catch (IOException e) 
    {
        e.printStackTrace();
    }

    Uri mImageUri = Uri.parse(file.getAbsolutePath());

    return mImageUri;
}

required permission

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Headpin answered 2/10, 2018 at 21:17 Comment(0)
A
1

You might be able to use the following for decoding, compressing and saving an image:

     @Override
     public void onClick(View view) {
                onItemSelected1();
                InputStream image_stream = null;
                try {
                    image_stream = getContentResolver().openInputStream(myUri);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                Bitmap image= BitmapFactory.decodeStream(image_stream );
                // path to sd card
                File path=Environment.getExternalStorageDirectory();
                //create a file
                File  dir=new File(path+"/ComDec/");
                dir.mkdirs();
                Date date=new Date();
                File file=new File(dir,date+".jpg");

                OutputStream out=null;
                try{
                    out=new FileOutputStream(file);
                    image.compress(format,size,out);
                    out.flush();
                    out.close();


                    MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");

                    image=null;


                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
                Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
            }
        });
Archivist answered 28/3, 2019 at 11:25 Comment(0)
D
0
removeStyles(content: string, property: string): string {
    const parser = new DOMParser();
    const doc = parser.parseFromString(content, 'text/html');

    // Remove inline styles that start with the specified property
    const elementsWithInlineStyles = doc.querySelectorAll('[style]');
    elementsWithInlineStyles.forEach(el => {
      const styleValue = el.getAttribute('style');
      if (styleValue) {
        const newStyleValue = this.filterInlineStyles(styleValue, property);
        if (newStyleValue) {
          el.setAttribute('style', newStyleValue); // Update the style attribute
        } else {
          el.removeAttribute('style'); // If no styles left, remove the style attribute
        }
      }
    });

    // Remove specific rules from <style> tags that start with the specified property
    const styleTags = doc.querySelectorAll('style');
    styleTags.forEach(styleTag => {
      const newStyleContent = this.filterStyleTagRules(styleTag.textContent, property);
      styleTag.textContent = newStyleContent;
    });

    return doc.body.innerHTML;
  }

  // Helper function to remove styles from inline style attributes
  filterInlineStyles(styleValue: string, property: string): string {
    return styleValue
      .split(';') // Split the style attribute into individual rules
      .filter(style => !style.trim().startsWith(property)) // Filter out rules that start with the specified property
      .join(';'); // Join the remaining rules back
  }

  // Helper function to remove CSS rules from <style> tag
  filterStyleTagRules(styleContent: string | null, property: string): string {
    if (!styleContent) return '';
    const rules = styleContent.split('}');
    return rules
      .filter(rule => !rule.includes(`${property}:`)) // Remove rules that include the specified property
      .map(rule => rule.trim() ? rule + '}' : '') // Rebuild valid CSS rules
      .join(' ');
  }
}
Dialecticism answered 9/8, 2024 at 0:17 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.