すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:IMG

最終更新日:Oct 28, 2024

Image Processing (IMG) は、イメージの処理を支援するためにObject Storage service (OSS) によって提供される、安全で費用対効果の高い信頼性の高いイメージ処理サービスです。 ソースイメージをOSSにアップロードした後、RESTful APIを呼び出して、いつでもどこでも、接続されたデバイスでイメージを処理できます。

使用上の注意

  • このトピックでは、中国 (杭州) リージョンのパブリックエンドポイントを使用します。 OSSと同じリージョンにある他のAlibaba CloudサービスからOSSにアクセスする場合は、内部エンドポイントを使用します。 OSSリージョンとエンドポイントの詳細については、「リージョン、エンドポイント、オープンポート」をご参照ください。

  • このトピックでは、アクセス資格情報は環境変数から取得します。 アクセス資格情報の設定方法の詳細については、「アクセス資格情報の設定」をご参照ください。

  • このトピックでは、OSSエンドポイントを使用してOSSClientインスタンスを作成します。 カスタムドメイン名またはSecurity Token Service (STS) を使用してOSSClientインスタンスを作成する場合は、「OSSClientインスタンスの作成」をご参照ください。

IMGパラメータを使用した画像処理

  • 単一のIMGパラメータを使用して画像を処理する

    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 {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. Do not include the bucket name in the full path. 
            String objectName = "exampleobject.jpg";
            // Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-resize.jpg. If a file with the same name already exists in the path, the processed image overwrites the file. Otherwise, the processed image is saved in the path. 
            String localPath = "D:\\localpath\\example-resize.jpg";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Resize the image to a height and width of 100 pixels. 
                String style = "image/resize,m_fixed,w_100,h_100";
                GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // Name the processed image example-resize.jpg and save the image to your local computer. 
                // If you specify only the name of a local file such as example-resize.jpg without specifying the local path of the file, the processed image is saved to the local path of the project to which the sample program belongs. 
                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();
                }
            }
        }
    }
  • 異なるIMGパラメータを使用して画像を処理する

    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 {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. Do not include the bucket name in the full path. 
            String objectName = "exampleobject.jpg";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Resize the image to a height and width of 100 pixels. 
                String style = "image/resize,m_fixed,w_100,h_100";
                GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // Name the processed image example-resize.jpg and save the image to your local computer. 
                // Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-resize.jpg. If a file with the same name already exists in the path, the processed image overwrites the file. Otherwise, the processed image is saved in the path. 
                // If you specify only the name of a local file such as example-resize.jpg without specifying the local path of the file, the processed image is saved to the local path of the project to which the sample program belongs. 
                ossClient.getObject(request, new File("D:\\localpath\\example-resize.jpg"));
    
                // Crop the image to a height and width of 100 pixels by setting the coordinate pair to (100, 100). 
                style = "image/crop,w_100,h_100,x_100,y_100";
                request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // Name the processed image example-crop.jpg and save the image to your local computer. 
                ossClient.getObject(request, new File("D:\\localpath\\example-crop.jpg"));
    
                // Rotate the image 90 degrees. 
                style = "image/rotate,90";
                request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // Name the processed image example-rotate.jpg and save the image to your local computer. 
                ossClient.getObject(request, new File("D:\\localpath\\example-rotate.jpg"));
    
                // Add a text watermark to the image. 
                // After the text watermark content is encoded in Base64, replace plus signs (+) in the encoded result with hyphens (-) and forward slashes (/) with underscores (_), and remove equal signs (=) at the end. Then, you can obtain the watermark string. 
                // Specify Hello World as the content of the text watermark, and encode the text content. Then, you can obtain the SGVsbG8gV29ybGQ string. 
                style = "image/watermark,text_SGVsbG8gV29ybGQ";
                request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // Name the processed image example-watermarktext.jpg and save the image to your local computer. 
                ossClient.getObject(request, new File("D:\\localpath\\example-watermarktext.jpg"));
    
                // Add an image watermark to the image. Make sure that the watermark image is stored in the bucket that stores the source image. 
                // After the full path of the watermark image is encoded in Base64, replace plus signs (+) in the encoded result with hyphens (-) and forward slashes (/) with underscores (_), and remove equal signs (=) at the end. Then, you can obtain the watermark string. 
                // Specify panda.jpg as the full path of the watermark image, and encode the full path. Then, you can obtain the cGFuZGEuanBn string. 
                style = "image/watermark,image_cGFuZGEuanBn";
                request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // Name the processed image example-watermarkimage.jpg and save the image to your local computer. 
                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();
                 }
            }
        }
    }
  • 複数のIMGパラメータを使用して画像を同時に処理する

    次のサンプルコードは、複数のIMGパラメーターを使用してイメージを同時に処理する方法の例を示しています。 IMGパラメーターはスラッシュ (/) で区切ります。

    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 {
            // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. Do not include the bucket name in the full path. 
            String objectName = "exampleobject.jpg";
            // Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-new.jpg. If a file with the same name already exists in the path, the processed image overwrites the file. Otherwise, the processed image is saved in the path. 
            String pathName = "D:\\localpath\\example-new.jpg";
            // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
            String region = "cn-hangzhou";
    
            // Create an OSSClient instance. 
            ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
            clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
            OSS ossClient = OSSClientBuilder.create()
            .endpoint(endpoint)
            .credentialsProvider(credentialsProvider)
            .clientConfiguration(clientBuilderConfiguration)
            .region(region)               
            .build();
    
            try {
                // Resize the image to a height and width of 100 pixels, and rotate the image 90 degrees. 
                String style = "image/resize,m_fixed,w_100,h_100/rotate,90";
                GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
                request.setProcess(style);
                // Name the processed image example-new.jpg and save the image to your local computer. 
                // If you specify only the name of a local file such as example-new.jpg without specifying the local path of the file, the processed image is saved to the local path of the project to which the sample program belongs. 
                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コンソールでイメージスタイルを作成し、そのスタイルに複数のIMGパラメーターをカプセル化できます。 次に、スタイルを使用して画像を処理できます。 詳細については、「イメージスタイル」をご参照ください。

次のサンプルコードは、イメージスタイルを使用してイメージを処理する方法の例を示しています。

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 {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. 
        String objectName = "exampleobject.jpg";
        // Specify the full path to which you want to save the processed image. Example: D:\\localpath\\example-new.jpg. If a file with the same name already exists in the path, the processed image overwrites the file. Otherwise, the processed image is saved in the path. 
        String pathName = "D:\\localpath\\example-new.jpg";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Use a custom image style to process the image. 
            // In this example, replace yourCustomStyleName with the name of the image style that you created in the OSS console. 
            String style = "style/yourCustomStyleName";
            GetObjectRequest request = new GetObjectRequest(bucketName, objectName);
            request.setProcess(style);
            // Name the processed image example-new.jpg and save the image to your local computer. 
            // If you specify only the name of a local file such as example-new.jpg without specifying the local path of the file, the processed image is saved to the local path of the project to which the sample program belongs. 
            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();
            }
        }
    }
}

処理された画像を保存する

デフォルトでは、IMGは処理済み画像を保存しません。 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 {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. 
        String sourceImage = "exampleimage.png";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Resize the image to a height and width of 100 pixels. 
            StringBuilder sbStyle = new StringBuilder();
            Formatter styleFormatter = new Formatter(sbStyle);
            String styleType = "image/resize,m_fixed,w_100,h_100";
            // Name the processed image example-resize.png and save the image to the bucket in which the source image is stored. 
            // Specify the full path of the object. Do not include the bucket name in the full path. 
            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();
            }
        }
    }
}

IMGパラメータを含む署名付きオブジェクトURLを生成する

プライベートオブジェクトのURLに署名する必要があります。 署名付きURLの末尾にIMGパラメーターを追加することはできません。 プライベートオブジェクトを処理する場合は、署名にIMGパラメーターを追加します。 次のサンプルコードは、署名にIMGパラメーターを追加する方法の例を示しています。

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 {
        // In this example, the endpoint of the China (Hangzhou) region is used. Specify your actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. Do not include the bucket name in the full path. 
        String objectName = "exampleobject.jpg";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";

        // Create an OSSClient instance. 
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);        
        OSS ossClient = OSSClientBuilder.create()
        .endpoint(endpoint)
        .credentialsProvider(credentialsProvider)
        .clientConfiguration(clientBuilderConfiguration)
        .region(region)               
        .build();

        try {
            // Resize the image to a height and width of 100 pixels, and rotate the image 90 degrees. 
            String style = "image/resize,m_fixed,w_100,h_100/rotate,90";
            // Set the validity period of the signed URL to 10 minutes. (The maximum validity period is 32400 seconds.)
            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();
            }
        }
    }
}

関連ドキュメント

  • サポートされるIMGパラメーターの詳細については、「概要」をご参照ください。

  • IMGの完全なサンプルコードについては、『GitHub』をご参照ください。