图片处理是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();
}
}
}
}
图片处理工具
您可以通过可视化图片处理工具ImageStyleViewer直观地看到OSS图片处理结果。
相关文档
文档内容是否对您有帮助?