Moataz
Moataz

Reputation: 657

How to get the name of image from url in this saveMyImage method

I use this code to save the image in the divice and it is working good but I have problem with image name, I don't know what to tape here (I download the image from url with picasso).

Here is the code:

void saveMyImage (String appName, String imageUrl, String imageName) {

    Bitmap bmImg = loadBitmap(imageUrl);
    File filename;
    try {
        String path1 = android.os.Environment.getExternalStorageDirectory()
                .toString();
        File file = new File(path1 + "/" + appName);
        if (!file.exists())
            file.mkdirs();
        filename = new File(file.getAbsolutePath() + "/" + imageName
                + ".jpg");
        FileOutputStream out = new FileOutputStream(filename);
        bmImg.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        ContentValues image = new ContentValues();
        image.put(Images.Media.TITLE, appName);
        image.put(Images.Media.DISPLAY_NAME, imageName);
        image.put(Images.Media.DESCRIPTION, "App Image");
        image.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
        image.put(Images.Media.MIME_TYPE, "image/jpg");
        image.put(Images.Media.ORIENTATION, 0);
        File parent = filename.getParentFile();
        image.put(Images.ImageColumns.BUCKET_ID, parent.toString()
                .toLowerCase().hashCode());
        image.put(Images.ImageColumns.BUCKET_DISPLAY_NAME, parent.getName()
                .toLowerCase());
        image.put(Images.Media.SIZE, filename.length());
        image.put(Images.Media.DATA, filename.getAbsolutePath());
        Uri result = getContentResolver().insert(
                Images.Media.EXTERNAL_CONTENT_URI, image);
        Toast.makeText(getApplicationContext(),
                "download in " + filename, Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

This is the call method in onCreate:

/* button to download the image */
download_image = findViewById(R.id.button_download);
checkPermission();
download_image.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        if (checkPermission()) {
            String URL = intent.getStringExtra("imageUrl");
            saveMyImage ("my app",URL,"i want to get the image name from the url");
        }
    }
});

I want to get the image name from the url, so how can I do that?

Upvotes: 1

Views: 236

Answers (1)

Antonis Radz
Antonis Radz

Reputation: 3097

Try this:

URI uri = new URI(URL);
URL videoUrl = uri.toURL();
File tempFile = new File(videoUrl.getFile());
String fileName = tempFile.getName();

Upvotes: 1

Related Questions