Java – extract the image into a blobstore
•
Java
In my application, I need to do the following:
I successfully uploaded, decompressed and saved the file @ blobstore, but the image seems to be broken When I download them from the blobstore (just blobstoreservice. Serve them), the image color is wrong, or partially displayed, or damaged in other ways Attempting to use imagesservice will also throw an exception I checked the size of the image before compression, and decompressed the file size when writing to the blobstore, and they look the same This is my code:
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); .... } }
Thank you very much for your time!
UPD: I found a feasible solution, but I still don't understand why the first solution failed
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); }
Solution
Because ZIS Read may not fill the entire buffer
Use the following instead
int len; while((len = zis.read(buffer)) >= 0){ ByteBuffer bb = ByteBuffer.wrap(buffer,len); writeChannel.write(bb); }
I hope it helps
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码