user2631279
user2631279

Reputation: 127

Copy existing png file and rename programmatically

I have a png file in a folder "Movies" on the sdcard. I want to copy and rename that file in the same folder. I'm confused on how to properly call the method SaveImage.

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    if (scanningResult != null) {
        isbn = scanningResult.getContents();
        SaveImage();
    }
    else{
        Toast toast = Toast.makeText(getApplicationContext(),
                "No scan data received!", Toast.LENGTH_SHORT);
        toast.show();
    }
}


private void SaveImage(Bitmap finalBitmap){
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/Movies/");
    String fname = "Image-"+ isbn +".jpg";
    File file = new File (myDir, fname);
    try {
        FileOutputStream out = new FileOutputStream(file);
        finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
        out.close();

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

Upvotes: 1

Views: 1808

Answers (3)

Rahul Sharma
Rahul Sharma

Reputation: 5834

Rename file:

File source =new File("abc.png");
File destination =new File("abcdef.png");
source.renameTo(destination);

Copy File:

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

Path source=Paths.get("abc.png");
Path destination=Paths.get("abcdef.png");
Files.copy(source, destination);

Upvotes: 1

Laurent
Laurent

Reputation: 1739

So your question is, how to properly call your SaveImage(Bitmap finalBitmap) method, right ? as your SaveImage method get a Bitmap as parameter you need to send it a Bitmap as parameter.

You can use BitmapFactory to create a Bitmap object from your file and send this Bitmap object to your SaveImage method :

String root = Environment.getExternalStorageDirectory().toString();
Bitmap bMap = BitmapFactory.decodeFile(root + "/Movies/myimage.png");
SaveImage(bMap);

Upvotes: 1

Harry T.
Harry T.

Reputation: 3527

I simply want to duplicate the same file and rename it

Thanks for making it more clearly. You can use this to copy from source file to destination file.

public void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dst);

    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    in.close();
    out.close();
}

Upvotes: 4

Related Questions