All Products
Search
Document Center

Object Storage Service:Image processing (Java SDK)

Last Updated:Jul 31, 2025

Image processing is a powerful, secure, cost-effective, and highly reliable image processing service provided by OSS. After you upload a source image to OSS, you can use simple RESTful APIs to process the image at any time and from any device connected to the Internet.

Precautions

  • In this topic, the public endpoint of the China (Hangzhou) region is used. To access OSS from other Alibaba Cloud services in the same region, use an internal endpoint. For details about supported regions and endpoints, see Regions and endpoints.

  • In this topic, access credentials are obtained from environment variables. For more information about how to configure access credentials, see Configure access credentials.

  • In this topic, an OSSClient instance is created by using an OSS endpoint. If you want to create an OSSClient instance by using custom domain names or Security Token Service (STS), see Configuration examples for common scenarios.

Process images using image processing parameters

  • Process an image using a single image processing parameter

    import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.GetObjectRequest; import java.io.File; public class Demo { public static void main(String[] args) throws Throwable { // The endpoint of the China (Hangzhou) region is used in this example. Specify the 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 bucket name. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. The full path cannot contain the bucket name. String objectName = "exampleobject.jpg"; // Specify the full path of the local file. Example: D:\\localpath\\example-resize.jpg. If the specified local file exists, it is overwritten. Otherwise, a new file is created. 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. // When the OSSClient instance is no longer used, call the shutdown method to release resources. 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 fixed width and height 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 it to the local device. // If you specify only the local file name, such as example-resize.jpg, without specifying the full path, the file 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(); } } } }
  • Process an image using different image processing parameters

    import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.GetObjectRequest; import java.io.File; public class Demo { public static void main(String[] args) throws Throwable { // The endpoint of the China (Hangzhou) region is used in this example. Specify the 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 bucket name. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. The full path cannot contain the bucket name. 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. // When the OSSClient instance is no longer used, call the shutdown method to release resources. 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 fixed width and height 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 it to the local device. // Specify the full path of the local file. Example: D:\\localpath\\example-resize.jpg. If the specified local file exists, it is overwritten. Otherwise, a new file is created. // If you specify only the local file name, such as example-resize.jpg, without specifying the full path, the file 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 width and height of 100 pixels, starting from the coordinate (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 it to the local device. ossClient.getObject(request, new File("D:\\localpath\\example-crop.jpg")); // Rotate the image by 90 degrees. style = "image/rotate,90"; request = new GetObjectRequest(bucketName, objectName); request.setProcess(style); // Name the processed image example-rotate.jpg and save it to the local device. ossClient.getObject(request, new File("D:\\localpath\\example-rotate.jpg")); // Add a text watermark to the image. // After the text content of the text watermark is Base64-encoded, replace plus signs (+) with hyphens (-), and forward slashes (/) with underscores (_) in the encoded string, and remove the equal signs (=) at the end to obtain the watermark string. // Specify Hello World as the text content of the text watermark. After the text content is encoded, the watermark string is SGVsbG8gV29ybGQ. style = "image/watermark,text_SGVsbG8gV29ybGQ"; request = new GetObjectRequest(bucketName, objectName); request.setProcess(style); // Name the processed image example-watermarktext.jpg and save it to the local device. 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 where the image is stored. // After the full path of the watermark image is Base64-encoded, replace plus signs (+) with hyphens (-), and forward slashes (/) with underscores (_) in the encoded string, and remove the equal signs (=) at the end to obtain the watermark string. // Specify panda.jpg as the full path of the watermark image. After the full path is encoded, the watermark string is cGFuZGEuanBn. style = "image/watermark,image_cGFuZGEuanBn"; request = new GetObjectRequest(bucketName, objectName); request.setProcess(style); // Name the processed image example-watermarkimage.jpg and save it to the local device. 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(); } } } }
  • Process an image using multiple image processing parameters at the same time

    When you use multiple image processing parameters to process an image, separate the parameters with forward slashes (/).

    import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.GetObjectRequest; import java.io.File; public class Demo { public static void main(String[] args) throws Throwable { // The endpoint of the China (Hangzhou) region is used in this example. Specify the 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 bucket name. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. The full path cannot contain the bucket name. String objectName = "exampleobject.jpg"; // Specify the full path of the local file. Example: D:\\localpath\\example-new.jpg. If the specified local file exists, it is overwritten. Otherwise, a new file is created. 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. // When the OSSClient instance is no longer used, call the shutdown method to release resources. 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 fixed width and height of 100 pixels, and then rotate the image by 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 it to the local device. // If you specify only the file name, such as example-new.jpg, without specifying the full path, the file 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(); } } } }

Process an image using an image style

You can create an image style in the OSS console. An image style encapsulates multiple image processing parameters and can be used to process images in batches. For more information, see Image styles.

The following code shows how to process an image using an image style.

import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; import com.aliyun.oss.model.GetObjectRequest; import java.io.File; public class Demo { public static void main(String[] args) throws Throwable { // The endpoint of the China (Hangzhou) region is used in this example. Specify the 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 bucket name. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. The full path cannot contain the bucket name. String objectName = "exampleobject.jpg"; // Specify the full path of the local file. Example: D:\\localpath\\example-new.jpg. If the specified local file exists, it is overwritten. Otherwise, a new file is created. 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. // When the OSSClient instance is no longer used, call the shutdown method to release resources. ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration(); clientBuilderConfiguration.setSignatureVersion(SignVersion.V4); OSS ossClient = OSSClientBuilder.create() .endpoint(endpoint) .credentialsProvider(credentialsProvider) .clientConfiguration(clientBuilderConfiguration) .region(region) .build(); try { // Process the image using a custom style. // 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 it to the local device. // If you specify only the file name, such as example-new.jpg, without specifying the full path, the file 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(); } } } }

Image processing persistence

By default, processed images are not saved. You can call the ImgSaveAs API to save the processed images to the same bucket as the source image.

The following code shows how to persist a processed image.

import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; 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 { // The endpoint of the China (Hangzhou) region is used in this example. Specify the 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 bucket name. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. The full path cannot contain the bucket name. 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. // When the OSSClient instance is no longer used, call the shutdown method to release resources. 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 fixed width and height 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 it to the current bucket. // Specify the full path of the object. The full path cannot contain the bucket name. 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 for a file that contains image processing parameters

The access URL for a private file contains a signature. You cannot add image processing parameters directly to a signed URL. To process a private file, you must add the image processing parameters to the signature. The following code provides an example:

import com.aliyun.oss.*; import com.aliyun.oss.common.auth.*; import com.aliyun.oss.common.comm.SignVersion; 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 { // The endpoint of the China (Hangzhou) region is used in this example. Specify the 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 bucket name. Example: examplebucket. String bucketName = "examplebucket"; // Specify the full path of the object. The full path cannot contain the bucket name. 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. // When the OSSClient instance is no longer used, call the shutdown method to release resources. 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 fixed width and height of 100 pixels, and then rotate the image by 90 degrees. String style = "image/resize,m_fixed,w_100,h_100/rotate,90"; // Set the expiration time of the signed URL to 10 minutes. (The maximum expiration time is 32,400 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(); } } } }

References