在Android pre api 14设备上使用libwebp将位图编码到webp
我想用在Android pre api 14设备上使用libwebp将位图编码到webp,android,bitmap,webp,Android,Bitmap,Webp,我想用libwebp在安卓2.x设备上将Bitmap编码到webp。下面是我的测试代码 public static int createWebPImage(Bitmap bitmap, String outFilePath) { Log.d(TAG, "create webp image"); ByteBuffer buffer = ByteBuffer.allocateDirect(BitmapCompat.getAllocationByteCount(bitmap));
libwebp
在安卓2.x设备上将Bitmap
编码到webp。下面是我的测试代码
public static int createWebPImage(Bitmap bitmap, String outFilePath) {
Log.d(TAG, "create webp image");
ByteBuffer buffer = ByteBuffer.allocateDirect(BitmapCompat.getAllocationByteCount(bitmap));
bitmap.copyPixelsToBuffer(buffer);
return nativeCreateWebPImage(buffer, bitmap.getWidth(), bitmap.getHeight(), outFilePath);
}
jni实现是
nativeCreateWebPImage(JNIEnv *env, jclass type, jobject directBuffer, jint width, jint height, jstring outFilePath_) {
const char *outFilePath = env->GetStringUTFChars(outFilePath_, 0);
int ret = 0;
FILE* file = NULL;
if ((file = fopen(outFilePath, "w+")) != NULL) {
uint8_t* buffer = (uint8_t *) env->GetDirectBufferAddress(directBuffer);
LOGD("size of the bitmap %lu", (unsigned long) env->GetDirectBufferCapacity(directBuffer));
uint8_t* output = (uint8_t *) malloc((size_t) env->GetDirectBufferCapacity(directBuffer));
size_t n = WebPEncodeRGBA(buffer, width, height, width, 0.9, &output);
if (n <= 0) {
LOGD("webp encode failed");
ret = -1;
} else {
LOGD("write to file");
if (fwrite(output, sizeof(uint8_t), n, file) != n) {
LOGD("write file error");
ret = -1;
}
}
free(output);
fclose(file);
} else {
LOGD("open file error %s", outFilePath);
ret = -1;
}
env->ReleaseStringUTFChars(outFilePath_, outFilePath);
return ret;
}
nativeCreateWebPImage(JNIEnv*env,jclass类型,jobject directBuffer,jint宽度,jint高度,jstring outFilePath_41;{
const char*outFilePath=env->GetStringUTFChars(outFilePath,0);
int-ret=0;
FILE*FILE=NULL;
如果((file=fopen(outFilePath,“w+”)!=NULL){
uint8_t*buffer=(uint8_t*)env->GetDirectBufferAddress(directBuffer);
LOGD(“位图大小%lu”,(无符号长)env->GetDirectBufferCapacity(directBuffer));
uint8_t*输出=(uint8_t*)malloc((size_t)env->GetDirectBufferCapacity(directBuffer));
size\u t n=WebPEncodeRGBA(缓冲区、宽度、高度、宽度、0.9和输出);
if(n释放StringUtfChars(出入口,出入口);
返回ret;
}
生成的文件已成功创建,但编码的图像已完全损坏。图像似乎填充了错误的数据。调用WebPEncodeRGBA
时参数是否错误?位图配置为bitmap.Config.ARGB_8888
如何使用API调用将位图
正确编码到webpWebPEncodeRGBA
?从Google读取后,我发现stride参数错误。应将其计为字节。然后我将encode函数调用改为
WebPEncodeRGBA(buffer, width, height, width * 4 /* stride in bytes */, 0.9, &output);
它奏效了。API 14之前的版本目前(截至2016年1月6日)有3.2%的设备访问Google Play().你确定你想让这么少的人遇到这些麻烦吗?@Budius目前我在Android 2.x设备上将位图压缩为jpeg格式,因此如果这个问题无法解决,我将继续在Android 2.x设备上使用jpeg格式。我更喜欢webp的原因是它的大小小于jpeg格式。