phonegap图片base64 android

时间:2013-01-14 16:28:56

标签: javascript image cordova camera base64

我想将从相机拍摄的照片作为base64字符串发送到服务器。我的问题是手机中的图片被破坏了。

我有一些console.logs在camera.getPicture的success函数中打印base64字符串,每当我打印字符串并解码图像时,它只显示顶部,就好像它是不完整的一样。 / p>

这是我的代码:

photo.capturePhoto = function(image_button_id) {
        navigator.camera.getPicture(function(image) {
            photo.onPhotoDataSuccess(image)
        }, onFail, {
            quality : 30,
            destinationType: destinationType.DATA_URL,
            correctOrientation : true
        });
    }

和成功函数:

photo.onPhotoDataSuccess = function(image) {
        console.log(image); //What this prints is an incomplete image when decoded
    }

此代码有什么问题?

这是使用以下内容解码的示例图片:http://www.freeformatter.com/base64-encoder.html enter image description here

我正在使用phonegap 2.2.0

3 个答案:

答案 0 :(得分:0)

您可以尝试提高图像质量。我记得如果质量设置为低,一些Android手机有问题。我知道这是一个很长的镜头,但值得尝试:)

答案 1 :(得分:0)

我认为console.log对可以打印的字符数有限制。将数据设置为图像标记的来源时会发生什么:

function onSuccess(imageData) {
    var image = document.getElementById('myImage');
    image.src = "data:image/jpeg;base64," + imageData;
}

此外,您可能想尝试将数据写入文件。

答案 2 :(得分:0)

我在android中遇到了同样的问题,究竟是什么问题_当我将图像编码成相应的Base64&如果图像尺寸更大(2mb或更多...并且还取决于图像质量和相机质量,可能取自2MP或5MP或可能是800万像素相机)那么将完整图像转换为Base64会遇到问题。你必须要减小关注图像的大小!我已经完成了我的工作Android code __ 获取Base64图像字符串

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Bitmap mBitmap= new decodeFile("<PATH_OF_IMAGE_HERE>");
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] b = baos.toByteArray();
        int i=b.length;
        String base64ImageString=android.util.Base64.encodeToString(b, 0, i, android.util.Base64.NO_WRAP);

转换为正确的位图

       /**
        *My Method that reduce the bitmap size.
        */
        private Bitmap decodeFile(String  fPath){

        //Decode image size
        BitmapFactory.Options opts = new BitmapFactory.Options();
        //opts.inJustDecodeBounds = true;
        opts.inDither=false;                     //Disable Dithering mode
        opts.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
        opts.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
        opts.inTempStorage=new byte[1024]; 

        BitmapFactory.decodeFile(fPath, opts);

        //The new size we want to scale to
        final int REQUIRED_SIZE=70;//or vary accoding to your need...

        //Find the correct scale value. It should be the power of 2.
        int scale=1;
        while(opts.outWidth/scale/2>=REQUIRED_SIZE && opts.outHeight/scale/2>=REQUIRED_SIZE)
            scale*=2;

        //Decode with inSampleSize
         opts.inSampleSize=scale;

        return BitmapFactory.decodeFile(fPath, opts);

   } 

我希望这会帮助其他面临同样问题的伙伴......谢谢!