【问题标题】:Image compression or conversion图像压缩或转换
【发布时间】:2015-06-25 02:54:06
【问题描述】:

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

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

Bitmap.CompressFormat 类允许压缩成以下 3 种格式:

  • JPEG
  • PNG
  • WEBP

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

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

感谢您的宝贵时间。

【问题讨论】:

    标签: java android image bitmap compression


    【解决方案1】:

    我不知道这些文件的压缩,但我创建了这个类以编程方式将文件上传到使用 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
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 2017-11-18
      • 2021-11-07
      • 1970-01-01
      • 2011-04-20
      相关资源
      最近更新 更多