@ PreAuthorize ( "isAuthenticated()" ) public E saveImage ( MultipartFile file , boolean createThumbnail , Integer thumbnailTargetSize ) throws Exception { InputStream is = null ; ByteArrayInputStream bais = null ; E imageToPersist = null ; try { is = file . getInputStream ( ) ; byte [ ] imageByteArray = IOUtils . toByteArray ( is ) ; // create a new instance (generic) imageToPersist = getEntityClass ( ) . newInstance ( ) ; // create a thumbnail if requested if ( createThumbnail ) { byte [ ] thumbnail = scaleImage ( imageByteArray , FilenameUtils . getExtension ( file . getOriginalFilename ( ) ) , thumbnailTargetSize ) ; imageToPersist . setThumbnail ( thumbnail ) ; } // set binary image data imageToPersist . setFile ( imageByteArray ) ; // detect dimensions bais = new ByteArrayInputStream ( imageByteArray ) ; BufferedImage bimg = ImageIO . read ( bais ) ; // set basic image properties imageToPersist . setWidth ( bimg . getWidth ( ) ) ; imageToPersist . setHeight ( bimg . getHeight ( ) ) ; imageToPersist . setFileType ( file . getContentType ( ) ) ; imageToPersist . setFileName ( file . getOriginalFilename ( ) ) ; // persist the image dao . saveOrUpdate ( imageToPersist ) ; } catch ( Exception e ) { throw new Exception ( "Could not create the Image in DB: " + e . getMessage ( ) ) ; } finally { IOUtils . closeQuietly ( is ) ; IOUtils . closeQuietly ( bais ) ; } return imageToPersist ; }
Method persists a given Image as a bytearray in the database