Unpack images in blobstore

in my application I need to do the following: 1. zip file with images (only jpg only now) and other things are uploaded to BlobStore. 2. The backend of the application should read the records from the downloaded zip code and save all the images found inside in BlobStore as offline files.

I have successfully downloaded, unzipped and saved @blobstore files, but the images seem to be broken. when I load them from BlobStore (just blobstoreService.serve them), the images have the wrong colors or are partially displayed or broken in other ways. attempting to use ImagesService also throws an exception. I checked the size of the images before they were buttoned, and the size of the files unpacked when writing to the blobstore block, and they look the same. here 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); .... } } 

Thanks so much for your time!

UPD: I found a job that works, 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); } 
+4
source share
1 answer

Due to zis.read (buffer), it may not fill the entire buffer.

Use instead

 int len; while((len = zis.read(buffer)) >= 0){ ByteBuffer bb = ByteBuffer.wrap(buffer, 0, len); writeChannel.write(bb); } 

Hope for this help

+1
source

Source: https://habr.com/ru/post/1385090/


All Articles