1

我有这个片段,它从相机捕捉照片并将其输出为 base64 字符串。

function onPhotoDataSuccess(imageData) {
  console.log("Image Data: "+imageData);

  var smallImage = document.getElementById('smallImage');
  smallImage.style.display = 'block';

  smallImage.src = "data:image/jpeg;base64," + imageData;
  console.log("Src:" + smallImage.src);
}

当我查看控制台日志时,第一个日志Image Data不完整,但第二个Src日志更长。

这是日志Image Data

09-18 17:00:24.591: D/CordovaLog(12097):
file:///android_asset/www/upload.html: Line 57 :
Image Data: /9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkz

而对于Src我得到的(你也可以解码它,没什么有趣的):

09-18 17:00:24.630: D/CordovaLog(12097):
file:///android_asset/www/upload.html: Line 71 :
Src:data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCAMgAeIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChY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fmOAeM0xpomBVgGB6g8gUjK7pgqOaaIGB4CjP1qhET29k3Plflnmp7aOBFzCgUd/Wl8hsdQD64pVhcA/vPyou+4WJcYB47UTDMWe

您可以看到通过imageData在两个日志中使用相同的变量,我无法得到相同的结果。而且,如果您在 中解码 base64 字符串Src,则图像不完整。

有人知道怎么修这个东西吗?

编辑jsfiddle显示 base64 的解码

编辑<img>HTML正文中的标签:

<img style="display:none;width:300px" id="smallImage" src="" />
4

1 回答 1

0

我建议您使用目标类型 asFILE_URI并从下面描述的方法中获取 base64

将目标类型设置为 FILE-URI 是推荐的方法,您可以在他们的文档中看到它

http://docs.phonegap.com/en/2.5.0/cordova_camera_camera.md.html

将目标类型指定为FILE_URI自身,在 imagedata 中,您将获取图像文件 uri 将其放置在图像标记中,然后将其放置在 HTML5 画布中,并且画布有一种名为 toDataURL 的方法,您将能够在其中获取相应图像的 base64。

检查下面的代码

function onPhotoDataSuccess(imageData)
     {

                var $img = $('<img/>');
                $img.attr('src', imageData);
                $img.css({position: 'absolute', left: '0px', top: '-999999em', maxWidth: 'none', width: 'auto', height: 'auto'});
                $img.bind('load', function() 
                {
                    var canvas = document.createElement("canvas");
                    canvas.width = $img.width();
                    canvas.height = $img.height();
                    var ctx = canvas.getContext('2d');
                    ctx.drawImage($img[0], 0, 0);
                    var dataUri = canvas.toDataURL('image/png');

                });
                $img.bind('error', function() 
                {
                    console.log('Couldnt convert photo to data URI');
                });

    }
于 2013-09-18T09:29:55.293 回答