SlideShare a Scribd company logo
1 of 3
Saving Image to Android device’s
Gallery – Phonegap Android
Actual blog post link: http://jbkflex.wordpress.com/2012/12/23/saving-image-to-android-devices-gallery-
phonegap-android/


Quick snippet of code that will help a Phonegap Android app to save an image to the Android device’s SD
Card and make it available to the Gallery app to show. The title of this post may be misleading but note
that when you save an image, you actually have to save it on the SD Card or the device’s memory. The
Gallery is just an app that shows the collection of images from various locations on the SD Card. So,
there’s nothing like saving an image directly to the Gallery.


Moreover I tried to save an image using the FileWriter – Phonegap API, but as it turned out, it can save
only text data on the device’s memory. So, only way to do it was write a Phonegap plugin, pass the image
data from JavaScript interface to the Java side and let the Java class save the image on the SD Card.
Well I am not going to talk on the entire plugin, but I will share the Java code,
The methods below should be included inside your plugin’s Java class. The idea is simple, whatever be
your image/ image data (eg. Base64 data), you take that image data and save it on the SD Card using the
FileOutputStream. You get the file path by querying the external storage public directory which is the first
line inside the savePhoto() method below. Now, after the image is saved you broadcast it through the
System’s Media Scanner so that it becomes available to the Android Gallery app and to other apps. Hope
this is clear, time for action now.


private String savePhoto(Bitmap bmp)


{


    //File imageFileFolder = new
File(Environment.getExternalStorageDirectory(),"MyFolder"); //when you need
to save the image inside your own folder in the SD Card
    File path = Environment.getExternalStoragePublicDirectory(
       Environment.DIRECTORY_PICTURES
    ); //this is the default location inside SD Card - Pictures folder
    //imageFileFolder.mkdir(); //when you create your own folder, you use this
line.
    FileOutputStream out = null;
    Calendar c = Calendar.getInstance();
    String date = fromInt(c.get(Calendar.MONTH))
+ fromInt(c.get(Calendar.DAY_OF_MONTH))
    + fromInt(c.get(Calendar.YEAR))
    + fromInt(c.get(Calendar.HOUR_OF_DAY))
    + fromInt(c.get(Calendar.MINUTE))
    + fromInt(c.get(Calendar.SECOND));
    File imageFileName = new File(path, date.toString() + ".jpg");
//imageFileFolder
    try
    {
        out = new FileOutputStream(imageFileName);
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
        out.flush();
        out.close();
        scanPhoto(imageFileName.toString());
        out = null;
    } catch (Exception e)
    {
        e.printStackTrace();
    }
    return imageFileName.toString();
}
private String fromInt(int val)
{
    return String.valueOf(val);
}


/* invoke the system's media scanner to add your photo to the Media
Provider's database,
* making it available in the Android Gallery application and to other apps.
*/
private void scanPhoto(String imageFileName)
{
    Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    File f = new File(imageFileName);
    Uri contentUri = Uri.fromFile(f);
    mediaScanIntent.setData(contentUri);
    //this.cordova.getContext().sendBroadcast(mediaScanIntent); //this is
deprecated
    this.cordova.getActivity().sendBroadcast(mediaScanIntent);
}
Note that I am not a Java developer, and you may need to modify this code as per your needs. But it
should work. First save your image (create a Phonegap Android app and test it) and after that you can
see it being displayed in the gallery app. I did collect this code by browsing the net and made it work
100%. Otherwise it was difficult for me, since I did not find any concrete answer on this. Leave a
suggestion if there is a better solution.

More Related Content

Recently uploaded

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Featured

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Saving Image to Android device’s Gallery – Phonegap Android

  • 1. Saving Image to Android device’s Gallery – Phonegap Android Actual blog post link: http://jbkflex.wordpress.com/2012/12/23/saving-image-to-android-devices-gallery- phonegap-android/ Quick snippet of code that will help a Phonegap Android app to save an image to the Android device’s SD Card and make it available to the Gallery app to show. The title of this post may be misleading but note that when you save an image, you actually have to save it on the SD Card or the device’s memory. The Gallery is just an app that shows the collection of images from various locations on the SD Card. So, there’s nothing like saving an image directly to the Gallery. Moreover I tried to save an image using the FileWriter – Phonegap API, but as it turned out, it can save only text data on the device’s memory. So, only way to do it was write a Phonegap plugin, pass the image data from JavaScript interface to the Java side and let the Java class save the image on the SD Card. Well I am not going to talk on the entire plugin, but I will share the Java code, The methods below should be included inside your plugin’s Java class. The idea is simple, whatever be your image/ image data (eg. Base64 data), you take that image data and save it on the SD Card using the FileOutputStream. You get the file path by querying the external storage public directory which is the first line inside the savePhoto() method below. Now, after the image is saved you broadcast it through the System’s Media Scanner so that it becomes available to the Android Gallery app and to other apps. Hope this is clear, time for action now. private String savePhoto(Bitmap bmp) { //File imageFileFolder = new File(Environment.getExternalStorageDirectory(),"MyFolder"); //when you need to save the image inside your own folder in the SD Card File path = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES ); //this is the default location inside SD Card - Pictures folder //imageFileFolder.mkdir(); //when you create your own folder, you use this line. FileOutputStream out = null; Calendar c = Calendar.getInstance(); String date = fromInt(c.get(Calendar.MONTH))
  • 2. + fromInt(c.get(Calendar.DAY_OF_MONTH)) + fromInt(c.get(Calendar.YEAR)) + fromInt(c.get(Calendar.HOUR_OF_DAY)) + fromInt(c.get(Calendar.MINUTE)) + fromInt(c.get(Calendar.SECOND)); File imageFileName = new File(path, date.toString() + ".jpg"); //imageFileFolder try { out = new FileOutputStream(imageFileName); bmp.compress(Bitmap.CompressFormat.JPEG, 100, out); out.flush(); out.close(); scanPhoto(imageFileName.toString()); out = null; } catch (Exception e) { e.printStackTrace(); } return imageFileName.toString(); } private String fromInt(int val) { return String.valueOf(val); } /* invoke the system's media scanner to add your photo to the Media Provider's database, * making it available in the Android Gallery application and to other apps. */ private void scanPhoto(String imageFileName) { Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); File f = new File(imageFileName); Uri contentUri = Uri.fromFile(f); mediaScanIntent.setData(contentUri); //this.cordova.getContext().sendBroadcast(mediaScanIntent); //this is deprecated this.cordova.getActivity().sendBroadcast(mediaScanIntent);
  • 3. } Note that I am not a Java developer, and you may need to modify this code as per your needs. But it should work. First save your image (create a Phonegap Android app and test it) and after that you can see it being displayed in the gallery app. I did collect this code by browsing the net and made it work 100%. Otherwise it was difficult for me, since I did not find any concrete answer on this. Leave a suggestion if there is a better solution.