3
votes

Simple i want to apply image compression using PNG/JPEG/Bitmap file.

Android we have Bitmap.CompressFormat to compressed our bitmap file and use for further operation.

Bitmap.CompressFormat class allow to compress in 3 format as below :

  • JPEG
  • PNG
  • WEBP

My query is i want to compress file in any on of below format :

I have found some image compression library like ImageIo & ImageMagick but didn't get any success. I want to use this file to upload on AmazonServer. Please guide me how to achieve this or is there any other option to upload image on amazon server.

Thanks for your time.

1

1 Answers

0
votes

I don't know about those file's compression but i created this class to upload files programatically into an Amazon s3 bucket that uses the Amazon SDK api:

package com.amazon.util;

    import com.amazonaws.AmazonClientException;
    import com.amazonaws.auth.PropertiesCredentials;
    import com.amazonaws.regions.Region;
    import com.amazonaws.regions.Regions;
    import com.amazonaws.services.s3.AmazonS3;
    import com.amazonaws.services.s3.AmazonS3Client;
    import com.amazonaws.services.s3.model.CannedAccessControlList;
    import com.amazonaws.services.s3.model.ObjectMetadata;
    import com.amazonaws.services.s3.model.PutObjectRequest;
    import com.amazonaws.services.s3.model.PutObjectResult;
    import com.amazonaws.services.s3.model.S3ObjectSummary;
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;

    public class AmazonS3Files {
        private static final String existingBucketName = "bucketName";
        private final String strProperties = "accessKey = MYACESSKEY \n"
                + "secretKey = my+secret+key";
        private static final String urlRegion = "https://s3.amazonaws.com/";
        public static final String urlPathS3 = urlRegion + existingBucketName;

        public String UploadFile(InputStream inFile, String pathDocument, String fileName) {
            return UploadFile(inFile, pathDocument, fileName, false);
        }

        public void deleteObjectsInFolder(String folderPath) {
            InputStream inputStreamCredentials = new ByteArrayInputStream(strProperties.getBytes());
            folderPath = folderPath.replace('\\', '/');
            if (folderPath.charAt(folderPath.length() - 1) == '/') {
                folderPath = folderPath.substring(0, folderPath.length() - 1);
            }
            if (folderPath.charAt(0) == '/') {
                folderPath = folderPath.substring(1, folderPath.length());
            }
            try {
                AmazonS3 s3Client = new AmazonS3Client(new PropertiesCredentials(inputStreamCredentials));
                for (S3ObjectSummary file : s3Client.listObjects(existingBucketName, folderPath).getObjectSummaries()) {
                    s3Client.deleteObject(existingBucketName, file.getKey());
                }
            } catch (IOException | AmazonClientException e) {
                System.out.println(e);
            }
        }

        public void deleteFile(String filePath) {
            InputStream inputStreamCredentials = new ByteArrayInputStream(strProperties.getBytes());
            filePath = filePath.replace('\\', '/');
            if (filePath.charAt(0) == '/') {
                filePath = filePath.substring(1, filePath.length());
            }
            try {
                AmazonS3 s3Client = new AmazonS3Client(new PropertiesCredentials(inputStreamCredentials));
                s3Client.deleteObject(existingBucketName, filePath);
            } catch (IOException | AmazonClientException e) {
                System.out.println(e);
            }
        }

        public String UploadFile(InputStream inFile, String pathDocument, String fileName, boolean bOverwiteFile) {
            InputStream inputStreamCredentials = new ByteArrayInputStream(strProperties.getBytes());
            String amazonFileUploadLocationOriginal;

            String strFileExtension = fileName.substring(fileName.lastIndexOf("."), fileName.length());

            fileName = fileName.substring(0, fileName.lastIndexOf("."));
            fileName = fileName.replaceAll("[^A-Za-z0-9]", "");
            fileName = fileName + strFileExtension;
            pathDocument = pathDocument.replace('\\', '/');
            try {
                if (pathDocument.charAt(pathDocument.length() - 1) == '/') {
                    pathDocument = pathDocument.substring(0, pathDocument.length() - 1);
                }
                if (pathDocument.charAt(0) == '/') {
                    pathDocument = pathDocument.substring(1, pathDocument.length());
                }
                amazonFileUploadLocationOriginal = existingBucketName + "/" + pathDocument;
                AmazonS3 s3Client = new AmazonS3Client(new PropertiesCredentials(inputStreamCredentials));
                s3Client.setRegion(Region.getRegion(Regions.SA_EAST_1));
                ObjectMetadata objectMetadata = new ObjectMetadata();
                objectMetadata.setContentLength(inFile.available());

                if (!bOverwiteFile) {
                    boolean bFileServerexists = true;
                    int tmpIntEnum = 0;
                    while (bFileServerexists) {
                        String tmpStrFile = fileName;
                        if (tmpIntEnum > 0) {
                            tmpStrFile = fileName.substring(0, fileName.lastIndexOf(".")) + "(" + tmpIntEnum + ")" + fileName.substring(fileName.lastIndexOf("."), fileName.length());
                        }
                        if (!serverFileExists(urlRegion + amazonFileUploadLocationOriginal + "/" + tmpStrFile)) {
                            bFileServerexists = false;
                            fileName = tmpStrFile;
                        }


                        tmpIntEnum++;
                    }
                }
                String strFileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                if (strFileType.toUpperCase().equals(".jpg".toUpperCase())) {
                    objectMetadata.setContentType("image/jpeg");
                } else if (strFileType.toUpperCase().equals(".png".toUpperCase())) {
                    objectMetadata.setContentType("image/png");
                } else if (strFileType.toUpperCase().equals(".gif".toUpperCase())) {
                    objectMetadata.setContentType("image/gif");
                } else if (strFileType.toUpperCase().equals(".gmap".toUpperCase())) {
                    objectMetadata.setContentType("text/plain");
                }

                PutObjectRequest putObjectRequest = new PutObjectRequest(amazonFileUploadLocationOriginal, fileName, inFile, objectMetadata).withCannedAcl(CannedAccessControlList.PublicRead);
                PutObjectResult result = s3Client.putObject(putObjectRequest);

                return "/" + pathDocument + "/" + fileName;
            } catch (Exception e) {
                // TODO: handle exception
                return null;
            }

        }

        public boolean serverFileExists(String URLName) {
            try {
                HttpURLConnection.setFollowRedirects(false);
                HttpURLConnection con =
                        (HttpURLConnection) new URL(URLName).openConnection();
                con.setRequestMethod("HEAD");
                return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
    }

And for usage with your file:

    BufferedImage img = null;
    try {
        img = ImageIO.read(new File("file.jpg"));  
       String strReturn = AmazonS3Files.UploadFile(new ByteArrayInputStream(((DataBufferByte)(img).getRaster().getDataBuffer()).getData()), "path/to/file", "newfilename.jpg"); //Returns null if the upload doesn't work or the s3 file path of the uploaded file

    } catch (IOException e) {
//Handle Exception
    }