java – 将图像解压缩到blobstore中
作者:互联网
在我的应用程序中,我需要执行以下操作:
1.带有图像的zip文件(仅限jpgs)和其他内容上传到BlobStore.
2.应用引擎后端应该从上传的zip读取条目,并将内部找到的所有图像保存为BlobStore作为独立文件.
我成功上传,解压缩和保存文件@ blobstore,但图像似乎被打破了.
当我从BlobStore下载它们(只是blobstoreService.serve它们)时,图像颜色错误,或部分显示,或以其他方式破坏.尝试使用ImagesService也会引发异常.我在压缩之前检查了图像的大小,并且在写入blobstore时解压缩文件的大小并且它们看起来相同.这是我的代码:
ZipInputStream zis = ...;
ZipEntry entry;
while ((entry =zis.getNextEntry()) !=null)
{
String fileName = entry.getName().toLowerCase();
if(fileName.indexOf(".jpg") != -1 || fileName.indexOf(".jpeg") != -1)
{
FileService fileService = FileServiceFactory.getFileService();
String mime = ctx.getMimeType(fileName);//getting mime from servlet context
AppEngineFile file = fileService.createNewBlobFile(mime, fileName);
boolean lock = true;
FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);
byte[] buffer = new byte[BlobstoreService.MAX_BLOB_FETCH_SIZE];
while(zis.read(buffer) >= 0)
{
ByteBuffer bb = ByteBuffer.wrap(buffer);
writeChannel.write(bb);
}
writeChannel.closeFinally();
BlobKey coverKey = fileService.getBlobKey(file);
....
}
}
非常感谢你的时间!
UPD:我找到了可行的解决办法,但我仍然不明白为什么第一个解决方案失败了.
int read;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while((read = zis.read()) >= 0)
{
baos.write(read);
if(baos.size() == BlobstoreService.MAX_BLOB_FETCH_SIZE)
{
ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
writeChannel.write(bb);
baos = new ByteArrayOutputStream();
}
}
if(baos.size() > 0)
{
ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());
writeChannel.write(bb);
}
解决方法:
因为zis.read(缓冲区)可能无法填充整个缓冲区.
请改用以下内容
int len;
while((len = zis.read(buffer)) >= 0){
ByteBuffer bb = ByteBuffer.wrap(buffer, 0, len);
writeChannel.write(bb);
}
希望这有帮助
标签:java,google-app-engine,blobstore 来源: https://codeday.me/bug/20190709/1417377.html