使用libjpegturbo压缩批量图片时出现奇怪的结果

时间:2013-08-22 10:22:55

标签: android bitmap android-ndk libjpeg-turbo turbojpeg

首先,我(想)做的事情: 压缩和缩小一批图片(jpg)。 让我们假设原始图片的尺寸为1600w x 1200h。 现在,我想要一个1600x1200的压缩副本和另一个800x600和400x300的压缩副本。

我用的是什么: 我正在使用libJpegTurob来实现这一目标。如果LibJpegTurob有问题,我会尝试使用android给定的方法。

已经尝试过: 首先,我使用了从Tom Gall(https://github.com/jberkel/libjpeg-turbo)移植的Java Wrapper。

在我开始使用超过4mb的图片之前,它非常好(在nexus 4上)。 基本上发生了什么是android抛出OutOfMemory异常。这种情况发生在我使用较小的图片(~1-2mb)但是一个接一个压缩的时候。

在nexus s等具有较低内存的预算设备上运行后,这变得更糟。 由低堆引起的问题,这就是我的想法。

那么,我想,我必须在c中这样做。 内存问题似乎已经解决,只要我在预算设备上使用小于3mb的图片。 在nexus 4上,我甚至可以压缩> 15mb的图片。

这是src图片。enter image description here

但是现在......问题。 第一张压缩图片看起来不错 enter image description here

但所有其他的看起来像这样 enter image description here或此enter image description here

只要我保持选择图片并压缩它们就会发生这种情况。

现在代码。

这是缩放和压缩发生的地方

    #include "_HelloJNI.h"

#include <errno.h>
#include <jni.h>
#include <sys/time.h>
#include <time.h>
#include <android/log.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <android/bitmap.h>
#include <unistd.h>
#include <setjmp.h>
#include "jpeglib.h"
#include "turbojpeg.h"


#define  LOG_TAG    "DEBUG"
#define  LOGI(...)  __android_log_print(ANDROID_LOG_INFO,LOG_TAG,__VA_ARGS__)
#define  LOGV(...)  __android_log_print(ANDROID_LOG_VERBOSE,LOG_TAG,__VA_ARGS__)
#define  LOGD(...)  __android_log_print(ANDROID_LOG_DEBUG,LOG_TAG,__VA_ARGS__)
#define  LOGE(...)  __android_log_print(ANDROID_LOG_ERROR,LOG_TAG,__VA_ARGS__)


int IMAGE_COMPRESS_QUALITY = 80;

typedef struct  {
    int width;
    int height;
}tSize;


JNIEXPORT jint JNICALL Java_com_example_LibJpegTurboTest_NdkCall_nativeCompress
(JNIEnv * env, jobject onj, jstring jniSrcImgPath, jstring jniDestDir, jstring jniDestImgName, jint jniSrcWidth, jint jniSrcHeight) {

    int pyramidRet = 0;

    tSize fileSize;
    fileSize.width = (int)jniSrcWidth;
    fileSize.height = (int)jniSrcHeight;

    const char* srcImgPath = (*env)->GetStringUTFChars(env, jniSrcImgPath, 0);
    const char* destDir = (*env)->GetStringUTFChars(env, jniDestDir, 0);
    const char* destFileName = (*env)->GetStringUTFChars(env, jniDestImgName, 0);

    pyramidRet = createPreviewPyramidUsingCustomScaling(srcImgPath, destDir, destFileName, fileSize, 4);

    return 0;
}

static tSize imageSizeForStep(int step, tSize *originalSize) {
    float factor = 1 / pow(2, step);

    return (tSize) {
        round(originalSize->width  * factor),
        round(originalSize->height * factor) };
}

int saveBitmapBufferImage(unsigned char *data, tSize *imageSize, char *destFileName, int quality) {

    int retValue = 1;
    int res = 0;
    unsigned long destinationJpegBufferSize = 0;
    tjhandle tjCompressHandle = NULL;
    unsigned char *destinationJpegBuffer = NULL;
    FILE *file = NULL;

    // jpgeg compress
    tjCompressHandle = tjInitCompress();
    if(tjCompressHandle == NULL) {
        retValue = -1;
        goto cleanup;
    } 

    res = tjCompress2(tjCompressHandle, data, imageSize->width, imageSize->width * tjPixelSize[TJPF_RGBX], imageSize->height, TJPF_RGBX, &destinationJpegBuffer, &destinationJpegBufferSize, 1,
    quality, TJFLAG_FASTUPSAMPLE);
    if(res < 0) {
        retValue = -1;
        goto cleanup;
    }

    file = fopen(destFileName, "wb");
    if(file == NULL) {
        retValue = -1;
        goto cleanup;
    } 

    long written = fwrite(destinationJpegBuffer, destinationJpegBufferSize, 1, file);
    retValue = (written == 1);

    cleanup:
    if(tjCompressHandle) {
        tjDestroy(tjCompressHandle);
    }
    if(destinationJpegBuffer) {
        tjFree(destinationJpegBuffer);
    }
    if(file) {
        fclose(file);
    }

    return retValue;
}


int createBitmapBufferFromFile(char *srcFileName, tSize imageDimensions, long *bytesPerRow, long *dataBufferSize, unsigned char **dataBuffer) {
    int retValue = 1;
    int res = 0;

    FILE *file = NULL;

    unsigned char* sourceJpegBuffer = NULL;
    long sourceJpegBufferSize = 0;

    tjhandle tjDecompressHandle = NULL;
    int fileWidth = 0, fileHeight = 0, jpegSubsamp = 0;

    unsigned char* temp = NULL;

    unsigned char* rotatedSourceJpegBuffer = NULL;
    tjhandle tjTransformHandle = NULL;

    file = fopen(srcFileName, "rb");
    if (file == NULL) {
        retValue = -1;
        goto cleanup;
    } 


    res = fseek(file, 0, SEEK_END);
    if(res < 0) {
        retValue = -1;
        goto cleanup;
    } 


    sourceJpegBufferSize = ftell(file);
    if(sourceJpegBufferSize <= 0) {
        retValue = -1;
        goto cleanup;
    } 

    sourceJpegBuffer = tjAlloc(sourceJpegBufferSize);
    if(sourceJpegBuffer == NULL) {
        retValue = -1;
        goto cleanup;
    } 


    res = fseek(file, 0, SEEK_SET);
    if(res < 0) {
        retValue = -1;
        goto cleanup;
    } 


    res = fread(sourceJpegBuffer, (long)sourceJpegBufferSize, 1, file);
    if(res != 1) {      
        retValue = -1;
        goto cleanup;
    } 


    tjDecompressHandle = tjInitDecompress();
    if(tjDecompressHandle == NULL) {        
        retValue = -1;
        goto cleanup;
    } 

    // decompress header to get image dimensions
    res = tjDecompressHeader2(tjDecompressHandle, sourceJpegBuffer, sourceJpegBufferSize, &fileWidth, &fileHeight, &jpegSubsamp);
    if(res < 0) {
        retValue = -1;
        goto cleanup;
    } 

    float destWidth = (float)imageDimensions.width;
    float destHeight = (float)imageDimensions.height;

    *bytesPerRow = destWidth * tjPixelSize[TJPF_RGBX];

    // buffer for uncompressed image-data
    *dataBufferSize = *bytesPerRow * destHeight;

    temp = tjAlloc(*dataBufferSize);
    if(temp == NULL) {  
        retValue = -1;
        goto cleanup;
    } 


    res = tjDecompress2(tjDecompressHandle,
                                 sourceJpegBuffer,
                                 sourceJpegBufferSize,
                                 temp,
                                 destWidth,
                                 *bytesPerRow,
                                 destHeight,
                                 TJPF_RGBX,
                                 TJ_FASTUPSAMPLE);
    if(res < 0) {
        retValue = -1;
        goto cleanup;
    } 

    *dataBuffer = temp;
    temp = NULL;

    cleanup:
    if(file) {
        fclose(file);
    }
    if(sourceJpegBuffer) {
        tjFree(sourceJpegBuffer);
    }
    if(tjDecompressHandle) {
        tjDestroy(tjDecompressHandle);
    }
    if(temp) {      
        tjFree(temp);
    }

    return retValue;
}



int createPreviewPyramidUsingCustomScaling(char* srcImgPath, char* destDir, char* destFileName, tSize orginalImgSize, int maxStep) {
    int retValue = 1;
    int res = 1;
    int success = 0;
    int loopStep = 0;
    tSize previewSize;

    long bytesPerRow;
    long oldBytesPerRow = 0;

    unsigned char* sourceDataBuffer = NULL;
    long sourceDataBufferSize = 0;

    unsigned char* destinationDataBuffer = NULL;
    long destinationDataBufferSize = 0;

    unsigned char* buf1 = NULL;
    unsigned char* buf2 = NULL;
    long workBufSize = 0;

    void* sourceRow = NULL;
    void* targetRow = NULL;

    char* destFilePrefix = "sample_";
    char* fooDestName;
    char* fooStrBuilder;


    tSize orginSizeTmp;
    orginSizeTmp.width = orginalImgSize.width;
    orginSizeTmp.height = orginalImgSize.height;

    previewSize = imageSizeForStep(1, &orginSizeTmp);
    long width = (long)previewSize.width;
    long height = (long)previewSize.height;


    int errorCode = 0;  
    errorCode = createBitmapBufferFromFile(srcImgPath, previewSize, &bytesPerRow, &sourceDataBufferSize, &buf1);
    if(errorCode != 1) {    
        retValue = errorCode;
        goto cleanup;
    } 

    workBufSize = sourceDataBufferSize; 
    buf2 = tjAlloc(workBufSize);
    if(buf2 == NULL) {      
        retValue = -1;
        goto cleanup;
    } else {
        memset(buf2,0,workBufSize); 
    }

    sourceDataBuffer = buf1;

    fooDestName = strcat(destDir, destFilePrefix);
    fooStrBuilder = strcat(fooDestName, "1_");
    fooDestName = strcat(fooStrBuilder, destFileName);    


    success = saveBitmapBufferImage(sourceDataBuffer, &previewSize, fooDestName, IMAGE_COMPRESS_QUALITY);
    if(success <= 0) {
        retValue = -1;
        goto cleanup;
    } 


    cleanup:
    if(sourceDataBuffer) {      
        tjFree(sourceDataBuffer);
    }
    if(destinationDataBuffer) {     
        tjFree(destinationDataBuffer);
    }

    return retValue;
}

开始压缩的Java部分..

private void invokeCompress(ArrayList<PictureItem> picturesToCompress) {
    if(picturesToCompress != null && picturesToCompress.size() > 0) {
        for(int i=0; i<picturesToCompress.size(); i++) {
            String srcPicturePath = picturesToCompress.get(i).getSrcImg();
            String destDir = "/storage/emulated/0/1_TEST_FOLDER/";
            String destFileName = getRandomString(4)+".jpg";

            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(srcPicturePath, options);

            try {
                ndkCall.compress(srcPicturePath, destDir, destFileName, options.outWidth, options.outHeight);
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
}

我做错了什么???

非常感谢!!

P.S。抱歉英文不好!

2 个答案:

答案 0 :(得分:3)

对我来说很好。你确定libjpegturbo源是有效且稳定的吗?

答案 1 :(得分:2)

您的代码似乎没问题,编写得很好并且可以正确处理错误。但是从我看到的问题可能是外部库中的错误,你可以通过卸载(或uninit)来测试它,然后重新加载和重新启动库,然后编码下一个文件。

您也可以尝试使用旧版本的lib来查看它是否有效。

第二个问题可能是空闲后指针未设置为NULL并开始将错误数据写入内存。您应该使用像valgrind这样的工具,或者将所有malloc映射到它自己的页面中,并使用只读内存页面填充它们(请参阅:mprotect),然后当您在错误的页面中写入程序时,程序将会发生段错误,您将看到问题。 / p>

我不是这个lib的专家,但请仔细检查文档和示例代码。也许有些东西需要在两个文件之间或每个文件之后调用,而第一个工作只是纯粹的运气。

另外:尝试更改您编码的文件的顺序,也许会有所帮助。