简体   繁体   中英

image compression using s3 and lambda in java

I am trying to fetch image from s3 bucket of aws in lambda fuction and i want to compress this image and upload back to destination bucket of aws s3. I tried to fetch file from s3 and compress it.but facing problem in uploading the compressed file

Finally this worked

public class TempComp implements RequestHandler<S3Event, String> {

    private static final float MAX_WIDTH = 100;
    private static final float MAX_HEIGHT = 100;
    private final String JPG_TYPE = (String) "jpg";
    private final String JPG_MIME = (String) "image/jpeg";
    private final String PNG_TYPE = (String) "png";
    private final String PNG_MIME = (String) "image/png";

    public String handleRequest(S3Event s3event, Context context) {
        try {
            S3EventNotificationRecord record = s3event.getRecords().get(0);

            String srcBucket = record.getS3().getBucket().getName();
            // Object key may have spaces or unicode non-ASCII characters.
            String srcKey = record.getS3().getObject().getKey()
                    .replace('+', ' ');
            srcKey = URLDecoder.decode(srcKey, "UTF-8");

            String dstBucket = srcBucket + "resized";
            String dstKey = "resized-" + srcKey;

            // Sanity check: validate that source and destination are different
            // buckets.
            if (srcBucket.equals(dstBucket)) {
                System.out
                        .println("Destination bucket must not match source bucket.");
                return "";
            }

            // Infer the image type.
            Matcher matcher = Pattern.compile(".*\\.([^\\.]*)").matcher(srcKey);
            if (!matcher.matches()) {
                System.out.println("Unable to infer image type for key "
                        + srcKey);
                return "";
            }
            String imageType = matcher.group(1);
            if (!(JPG_TYPE.equals(imageType)) && !(PNG_TYPE.equals(imageType))) {
                System.out.println("Skipping non-image " + srcKey);
                return "";
            }

            // Download the image from S3 into a stream
            AmazonS3 s3Client = new AmazonS3Client();
            S3Object s3Object = s3Client.getObject(new GetObjectRequest(
                    srcBucket, srcKey));

            InputStream objectData = s3Object.getObjectContent();
      //      int b=objectData.read();

            // Read the source image
            BufferedImage srcImage = ImageIO.read(objectData);
       //     BufferedImage destImage = srcImage;


            Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
            if (!writers.hasNext())
              throw new IllegalStateException("No writers found");
            ImageWriter writer = (ImageWriter) writers.next();
            ByteArrayOutputStream os=new ByteArrayOutputStream() ;
            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
            writer.setOutput(ios);
            ImageWriteParam param = writer.getDefaultWriteParam();
            // compress to a given quality
            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
            param.setCompressionQuality(0.5f);
             // appends a complete image stream containing a single image and
            //associated stream and image metadata and thumbnails to the output
            writer.write(null, new IIOImage(srcImage, null, null), param);
            System.out.print("file is compressed");


            ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());

            //InputStream is = new ByteArrayInputStream(retValue);
            BufferedImage destImage = ImageIO.read(is);

             ByteArrayOutputStream os1 = new ByteArrayOutputStream();
             ImageIO.write(destImage, imageType, os1);
             InputStream is1 = new ByteArrayInputStream(os1.toByteArray()); 


             // Set Content-Length and Content-Type
             ObjectMetadata meta = new ObjectMetadata();
             meta.setContentLength(os1.size());
             System.out.println(os1.size());
             if (JPG_TYPE.equals(imageType)) {
                 meta.setContentType(JPG_MIME);
             }
             if (PNG_TYPE.equals(imageType)) {
                 meta.setContentType(PNG_MIME);
             }

             // Uploading to S3 destination bucket
             System.out.println("Writing to: " + dstBucket + "/" + dstKey);
             s3Client.putObject(dstBucket, dstKey, is1, meta);
             System.out.println("Successfully resized " + srcBucket + "/"
                     + srcKey + " and uploaded to " + dstBucket + "/" + dstKey);
             return "Ok";
         } catch (IOException e) {
             throw new RuntimeException(e);
         }


}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM