图像压缩或转换

时间:2015-04-18 04:48:03

标签: java android image bitmap compression

简单我想使用PNG / JPEG /位图文件应用图像压缩。

Android我们Bitmap.CompressFormat压缩我们的位图文件并用于进一步操作。

Bitmap.CompressFormat类允许以3种格式压缩,如下所示:

  • JPEG
  • PNG
  • WEBP

我的查询是我想以下列格式压缩文件:

我找到了一些图像压缩库,如ImageIo& ImageMagick但没有取得任何成功。我想使用此文件在AmazonServer上传。请指导我如何实现这一点,或者是否有任何其他选项可以在亚马逊服务器上传图像。

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

我不知道那些文件的压缩,但我创建了这个类,以编程方式将文件上传到使用Amazon SDK API的Amazon s3存储桶中:

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;
            }
        }
    }

用于您的文件:

    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
    }