Cordova新手求助:如何拍照并在Gallery页面使用照片
How to Pass Captured Photo to Gallery Page in Cordova
Hey there! Let's get that captured photo over to your Gallery page step by step. First, let's fix up your existing camera logic, then handle passing the image data between pages.
1. Fix the Camera Callback Logic
Your current onSuccess function isn't correctly handling the image data, and you're not triggering navigation to the Gallery page yet. Let's adjust that:
Updated Camera Trigger Code (on your main page)
document.getElementById('photo').addEventListener('click', function() { navigator.camera.getPicture(onSuccess, onFail, { quality: 25, destinationType: Camera.DestinationType.DATA_URL }); function onSuccess(imageData) { // Store the base64 image data in localStorage to access it on the Gallery page localStorage.setItem('capturedPhoto', imageData); // Navigate to your Gallery page (adjust the URL to match your actual page filename) window.location.href = 'Gallery.html'; } function onFail(message) { alert('Failed because: ' + message); } });
Quick Notes:
- We use
localStorage.setItem()to save the base64 image data temporarily. Your quality is set to 25, so the data size will be small enough for this method. window.location.hrefnavigates directly to your Gallery page—double-check the filename matches exactly (it's case-sensitive on some platforms!).
2. Display the Photo on the Gallery Page
Now, on your Gallery.html page, we'll retrieve the stored image data and render it:
Gallery Page HTML
<div id="imageGallery"> <img src="" alt="Captured Photo" id="galleryImg" style="width: 130px; height: auto;" /> </div> <script src="cordova.js"></script> <script src="gallery-script.js"></script> <!-- Or paste the JS directly in the HTML -->
Gallery Page JavaScript
// Wait for Cordova to fully load before running any device-related code document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // Get the stored photo data from localStorage const capturedPhoto = localStorage.getItem('capturedPhoto'); if (capturedPhoto) { // Render the image in the gallery const galleryImg = document.getElementById('galleryImg'); galleryImg.src = `data:image/jpeg;base64,${capturedPhoto}`; // Optional: Clear the stored data after displaying so it doesn't persist localStorage.removeItem('capturedPhoto'); } else { // Handle case where no photo was captured alert('No photo found to display!'); } }
3. Critical Pre-Checks
- Ensure you've installed the Cordova Camera plugin correctly:
cordova plugin add cordova-plugin-camera - Always wrap Cordova API calls (like camera access or localStorage usage) inside the
devicereadyevent listener—this guarantees Cordova is fully initialized before your code runs. - If you're using a framework like jQuery Mobile for navigation, adjust the page jump logic to match the framework's routing, but the localStorage approach for passing data will still work.
内容的提问来源于stack exchange,提问作者MANDO
相关产品推荐
相关产品推荐

