圖片處理是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圖片處理結果。
相關文檔
文檔內容是否對您有幫助?