全部產品
Search
文件中心

Object Storage Service:Java圖片處理

更新時間:Oct 25, 2024

圖片處理是OSS提供的海量、安全、低成本、高可靠的圖片處理服務。原始圖片上傳到OSS後,您可以通過簡單的RESTful介面,在任何時間、任何地點、任何互連網裝置上對圖片進行處理。

注意事項

  • 本文以華東1(杭州)外網Endpoint為例。如果您希望通過與OSS同地區的其他阿里雲產品訪問OSS,請使用內網Endpoint。關於OSS支援的Region與Endpoint的對應關係,請參見OSS訪問網域名稱、資料中心、開放連接埠

  • 本文以從環境變數讀取存取憑證為例。如何配置訪問憑證,請參見Java配置訪問憑證

  • 本文以OSS網域名稱建立OSSClient為例。如果您希望通過自訂網域名、STS等方式建立OSSClient,請參見建立OSSClient

使用圖片處理參數處理圖片

  • 使用單個圖片處理參數處理圖片

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.model.GetObjectRequest;
    import java.io.File;
    
    public class Demo {
        public static void main(String[] args) throws Throwable {
            // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填寫Bucket名稱,例如examplebucket。
            String bucketName = "examplebucket";
            // 填寫Object完整路徑。Object完整路徑中不能包含Bucket名稱。
            String objectName = "exampleobject.jpg";
            // 填寫本地檔案的完整路徑,例如D:\\localpath\\example-resize.jpg。如果指定的本地檔案存在會覆蓋,不存在則建立。
            String localPath = "D:\\localpath\\example-resize.jpg";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // 將圖片縮放為固定寬高100 px。
                String style = "image/resize,m_fixed,w_100,h_100";
                GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // 將處理後的圖片命名為example-resize.jpg並儲存到本地。
                // 如果未指定本地路徑只填寫了本地檔案名稱(例如example-resize.jpg),則檔案預設儲存到樣本程式所屬專案對應本地路徑中。
                ossClient.getObject(request, new File(localPath));
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • 使用不同的圖片處理參數處理圖片

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.model.GetObjectRequest;
    import java.io.File;
    
    public class Demo {
        public static void main(String[] args) throws Throwable {
            // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填寫Bucket名稱,例如examplebucket。
            String bucketName = "examplebucket";
            // 填寫Object完整路徑。Object完整路徑中不能包含Bucket名稱。
            String objectName = "exampleobject.jpg";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // 將圖片縮放為固定寬高100 px。
                String style = "image/resize,m_fixed,w_100,h_100";
                GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // 將處理後的圖片命名為example-resize.jpg並儲存到本地。
                // 填寫本地檔案的完整路徑,例如D:\\localpath\\example-resize.jpg。如果指定的本地檔案存在會覆蓋,不存在則建立。
                // 如果未指定本地路徑只填寫了本地檔案名稱(例如example-resize.jpg),則檔案預設儲存到樣本程式所屬專案對應本地路徑中。
                ossClient.getObject(request, new File("D:\\localpath\\example-resize.jpg"));
    
                // 從座標(100,100)開始,將圖片裁剪為寬高100 px。
                style = "image/crop,w_100,h_100,x_100,y_100";
                request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // 將處理後的圖片命名為example-crop.jpg並儲存到本地。
                ossClient.getObject(request, new File("D:\\localpath\\example-crop.jpg"));
    
                // 將圖片旋轉90°。
                style = "image/rotate,90";
                request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // 將處理後的圖片命名為example-rotate.jpg並儲存到本地。
                ossClient.getObject(request, new File("D:\\localpath\\example-rotate.jpg"));
    
                // 在圖片中添加文字浮水印。
                // 文字浮水印的文字內容經過Base64編碼後,再將編碼結果中的加號(+)替換成短劃線(-),正斜線(/)替換成底線(_)並去掉尾部的等號(=),從而得到浮水印字串。
                // 指定文字浮水印的文字內容為Hello World,文字內容進行編碼處理後得到的浮水印字串為SGVsbG8gV29ybGQ。
                style = "image/watermark,text_SGVsbG8gV29ybGQ";
                request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // 將處理後的圖片命名為example-watermarktext.jpg並儲存到本地。
                ossClient.getObject(request, new File("D:\\localpath\\example-watermarktext.jpg"));
    
                // 在圖片中添加圖片浮水印。請確保浮水印圖片已儲存在圖片所在Bucket中。
                // 浮水印圖片的完整路徑經過Base64編碼後,再將編碼結果中的加號(+)替換成短劃線(-),正斜線(/)替換成底線(_)並去掉尾部的等號(=),從而得到浮水印字串。
                // 指定浮水印圖片的完整路徑為panda.jpg,完整路徑進行編碼處理後得到的浮水印字串為cGFuZGEuanBn。
                style = "image/watermark,image_cGFuZGEuanBn";
                request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // 將處理後的圖片命名為example-watermarkimage.jpg並儲存到本地。
                ossClient.getObject(request, new File("D:\\localpath\\example-watermarkimage.jpg"));
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }
  • 同時使用多個圖片處理參數處理圖片

    使用多個圖片處理參數處理同一個圖片時,sytle中的多個參數之間以正斜線(/)分隔。

    import com.aliyun.oss.*;
    import com.aliyun.oss.common.auth.*;
    import com.aliyun.oss.model.GetObjectRequest;
    import java.io.File;
    
    public class Demo {
        public static void main(String[] args) throws Throwable {
            // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // 填寫Bucket名稱,例如examplebucket。
            String bucketName = "examplebucket";
            // 填寫Object完整路徑。Object完整路徑中不能包含Bucket名稱。
            String objectName = "exampleobject.jpg";
            // 填寫本地檔案的完整路徑,例如D:\\localpath\\example-new.jpg。如果指定的本地檔案存在會覆蓋,不存在則建立。
            String pathName = "D:\\localpath\\example-new.jpg";
            // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
            String region = "cn-hangzhou";
    
            // 建立OSSClient執行個體。
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // 將圖片縮放為固定寬高100 px後,再旋轉90°。
                String style = "image/resize,m_fixed,w_100,h_100/rotate,90";
                GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // 將處理後的圖片命名為example-new.jpg並儲存到本地。
                // 如果未指定本地路徑只填寫了檔案名稱(例如example-new.jpg),則檔案預設儲存到樣本程式所屬專案對應本地路徑中。
                ossClient.getObject(request, new File("D:\\localpath\\example-new.jpg"));
            } catch (OSSException oe) {
                System.out.println("Caught an OSSException, which means your request made it to OSS, "
                        + "but was rejected with an error response for some reason.");
                System.out.println("Error Message:" + oe.getErrorMessage());
                System.out.println("Error Code:" + oe.getErrorCode());
                System.out.println("Request ID:" + oe.getRequestId());
                System.out.println("Host ID:" + oe.getHostId());
            } catch (ClientException ce) {
                System.out.println("Caught an ClientException, which means the client encountered "
                        + "a serious internal problem while trying to communicate with OSS, "
                        + "such as not being able to access the network.");
                System.out.println("Error Message:" + ce.getMessage());
            } finally {
                if (ossClient != null) {
                    ossClient.shutdown();
                }
            }
        }
    }

使用圖片樣式處理圖片

您可以通過OSS管理主控台建立圖片樣式將多個圖片處理參數封裝在一個樣式中,然後使用樣式批量處理圖片。具體操作,請參見圖片樣式

以下代碼展示了使用圖片樣式處理圖片。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.model.GetObjectRequest;
import java.io.File;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Object完整路徑。Object完整路徑中不能包含Bucket名稱。
        String objectName = "exampleobject.jpg";
        // 填寫本地檔案的完整路徑,例如D:\\localpath\\example-new.jpg。如果指定的本地檔案存在會覆蓋,不存在則建立。
        String pathName = "D:\\localpath\\example-new.jpg";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 使用自訂樣式處理圖片。
            // yourCustomStyleName填寫通過OSS管理主控台建立的圖片樣式名稱。
            String style = "style/yourCustomStyleName";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(style);
            // 將處理後的圖片命名為example-new.jpg並儲存到本地。
            // 如果未指定本地路徑只填寫了檔案名稱(例如example-new.jpg),則檔案預設儲存到樣本程式所屬專案對應本地路徑中。
            ossClient.getObject(request, new File(pathName));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

圖片處理持久化

圖片處理服務預設不儲存處理後的圖片,您可以通過ImgSaveAs介面將圖片儲存到原圖片所在儲存空間。

以下代碼展示了圖片處理持久化操作。

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.common.utils.IOUtils;
import com.aliyun.oss.model.GenericResult;
import com.aliyun.oss.model.ProcessObjectRequest;
import java.util.Formatter;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Object完整路徑。Object完整路徑中不能包含Bucket名稱。
        String sourceImage = "exampleimage.png";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 將圖片縮放為固定寬高100 px。
            StringBuilder sbStyle = new StringBuilder();
            Formatter styleFormatter = new Formatter(sbStyle);
            String styleType = "image/resize,m_fixed,w_100,h_100";
            // 將處理後的圖片命名為example-resize.png並儲存到當前Bucket。
            // 填寫Object完整路徑。Object完整路徑中不能包含Bucket名稱。
            String targetImage = "example-resize.png";
            styleFormatter.format("%s|sys/saveas,o_%s,b_%s", styleType,
                    BinaryUtil.toBase64String(targetImage.getBytes()),
                    BinaryUtil.toBase64String(bucketName.getBytes()));
            System.out.println(sbStyle.toString());
            ProcessObjectRequest request = new ProcessObjectRequest(bucketName, sourceImage, sbStyle.toString());
            GenericResult processResult = ossClient.processObject(request);
            String json = IOUtils.readStreamAsString(processResult.getResponse().getContent(), "UTF-8");
            processResult.getResponse().getContent().close();
            System.out.println(json);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

產生帶圖片處理參數的檔案簽名URL

私人檔案的訪問URL帶有簽名。OSS不支援在帶簽名的URL後直接添加圖片處理參數。如果您想要對私人檔案進行圖片處理,需要將圖片處理參數加入到簽名中,相關的程式碼範例如下:

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import java.net.URL;
import java.util.Date;

public class Demo {
    public static void main(String[] args) throws Throwable {
        // Endpoint以華東1(杭州)為例,其它Region請按實際情況填寫。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填寫Bucket名稱,例如examplebucket。
        String bucketName = "examplebucket";
        // 填寫Object完整路徑。Object完整路徑中不能包含Bucket名稱。
        String objectName = "exampleobject.jpg";
        // 填寫Bucket所在地區。以華東1(杭州)為例,Region填寫為cn-hangzhou。
        String region = "cn-hangzhou";

        // 建立OSSClient執行個體。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // 將圖片縮放為固定寬高100 px後,再旋轉90°。
            String style = "image/resize,m_fixed,w_100,h_100/rotate,90";
            // 指定簽名URL到期時間為10分鐘。(最長到期時間為32400秒)
            Date expiration = new Date(new Date().getTime() + 1000 * 60 * 10 );
            GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
            req.setExpiration(expiration);
            req.setProcess(style);
            URL signedUrl = ossClient.generatePresignedUrl(req);
            System.out.println(signedUrl);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

相關文檔

  • 關於圖片處理支援的參數說明,請參見處理參數

  • 關於圖片處理的完整範例程式碼,請參見GitHub樣本