Image Processing (IMG) provided by Object Storage Service (OSS) is a secure, cost-effective, and highly reliable image processing service that can process large numbers of images. After you upload source images to OSS, you can call RESTful API operations to process the images on a device that is connected over the Internet anytime, anywhere.

Use IMG parameters to process images

  • Use a single IMG parameter to process an image
    import com.aliyun.oss.*;
    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 the actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. The full path cannot contain the name of the bucket. 
            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, a new file is created. 
            String localPath = "D:\\localpath\\example-resize.jpg";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            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. 
                // By default, if you only specify 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();
                }
            }
        }
    }
  • Use different IMG parameters to process an image
    import com.aliyun.oss.*;
    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 the actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. The full path cannot contain the name of the bucket. 
            String objectName = "exampleobject.jpg";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            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, a new file is created. 
                // By default, if you only specify 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();
                }
            }
        }
    }
  • Use multiple IMG parameters to process an image at the same time

    The following code provides an example on how to use multiple IMG parameters to process an image at the same time. Separate the IMG parameters with forward slashes (/).

    import com.aliyun.oss.*;
    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 the actual endpoint. 
            String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
            String accessKeyId = "yourAccessKeyId";
            String accessKeySecret = "yourAccessKeySecret";
            // Specify the name of the bucket. Example: examplebucket. 
            String bucketName = "examplebucket";
            // Specify the full path of the object. The full path cannot contain the name of the bucket. 
            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, a new file is created. 
            String pathName = "D:\\localpath\\example-new.jpg";
    
            // Create an OSSClient instance. 
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    
            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. 
                // By default, if you only specify 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();
                }
            }
        }
    }

Use an image style to process an image

You can create an image style in the OSS console and encapsulate multiple IMG parameters in the style. Then, you can use the style to process images. For more information, see Image styles.

The following code provides an example on how to use an image style to process an image:
import com.aliyun.oss.*;
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 the actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path cannot contain the name of the bucket. 
        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, a new file is created. 
        String pathName = "D:\\localpath\\example-new.jpg";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // Use the custom style to process the image. 
            // Set yourCustomStyleName to the name of the image style that you create 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. 
            // By default, if you only specify 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();
            }
        }
    }
}

Save processed images

By default, IMG does not save processed images. You can call the ImgSaveAs operation to save the images to the bucket in which the source images are stored.

The following code provides an example on how to save a processed image:
import com.aliyun.oss.*;
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 the actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path cannot contain the name of the bucket. 
        String sourceImage = "exampleimage.png";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        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. The full path cannot contain the name of the 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();
            }
        }
    }
}

Generate a signed URL that includes IMG parameters for an object

URLs of private objects must be signed. IMG parameters cannot be added to a signed URL. If you want to process a private object, add IMG parameters to the signature. The following code provides an example on how to add IMG parameters to the signature:
import com.aliyun.oss.*;
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 the actual endpoint. 
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to access OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // Specify the name of the bucket. Example: examplebucket. 
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path cannot contain the name of the bucket. 
        String objectName = "exampleobject.jpg";

        // Create an OSSClient instance. 
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        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. 
            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();
            }
        }
    }
}

References

  • For more information about the supported IMG parameters, see Parameters.
  • For more information about the complete sample code for IMG, visit GitHub.