图片处理是OSS提供的海量、安全、低成本、高可靠的图片处理服务。原始图片上传到OSS后,您可以通过简单的RESTful接口,在任何时间、任何地点、任何互联网设备上对图片进行处理。
注意事项
- 本文以华东1(杭州)外网Endpoint为例。如果您希望通过与OSS同地域的其他阿里云产品访问OSS,请使用内网Endpoint。关于OSS支持的Region与Endpoint的对应关系,请参见OSS地域和访问域名。 
- 本文以OSS域名新建OSSClient为例。如果您希望通过自定义域名、STS等方式新建OSSClient,请参见初始化。 
使用图片处理参数处理图片
- 使用单个图片处理参数处理图片并保存为本地图片 - using System; using System.IO; using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Util; namespace Samples { public class Program { public static void Main(string[] args) { // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 var endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // 指定原图所在的Bucket名称,例如examplebucket。 var bucketName = "examplebucket"; // 指定原图名称。如果图片不在Bucket根目录,需携带图片完整路径,例如exampledir/example.jpg。 var objectName = "exampledir/example.jpg"; // 指定原图所在的本地完整路径。 var localImageFilename = "D:\\localpath\\example.jpg"; // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。 const string region = "cn-hangzhou"; // 创建ClientConfiguration实例,按照您的需要修改默认参数。 var conf = new ClientConfiguration(); // 设置v4签名。 conf.SignatureVersion = SignatureVersion.V4; // 创建OssClient实例。 var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); try { // 将图片缩放为固定宽高100 px。 var process = "image/resize,m_fixed,w_100,h_100"; var ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process)); // 指定处理后的图片名称。 WriteToFile(localImageFilename, ossObject.Content); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } } private static void WriteToFile(string filePath, Stream stream) { using (var requestStream = stream) { using (var fs = File.Open(filePath, FileMode.OpenOrCreate)) { IoUtils.WriteTo(stream, fs); } } } } }
- 使用不同的图片处理参数处理图片并分别保存为本地图片 - using System; using System.IO; using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Util; namespace Samples { public class Program { public static void Main(string[] args) { // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 var endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // 指定原图所在的Bucket名称,例如examplebucket。 var bucketName = "examplebucket"; // 指定原图名称。如果图片不在Bucket根目录,需携带图片完整路径,例如exampledir/example.jpg。 var objectName = "exampledir/example.jpg"; // 指定原图所在的本地完整路径。 var localImageFilename = "D:\\localpath\\example.jpg"; // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。 const string region = "cn-hangzhou"; // 创建ClientConfiguration实例,按照您的需要修改默认参数。 var conf = new ClientConfiguration(); // 设置v4签名。 conf.SignatureVersion = SignatureVersion.V4; // 创建OssClient实例。 var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); try { // 若目标图片不在目标Bucket内,需上传图片到目标Bucket。 // client.PutObject(bucketName, objectName, localImageFilename); // 将图片缩放为固定宽高100 px。 var process = "image/resize,m_fixed,w_100,h_100"; var ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process)); // 指定处理后的图片名称。 WriteToFile(localImageFilename, ossObject.Content); // 从坐标(100,100)开始,将图片裁剪为宽高100 px。 process = "image/crop,w_100,h_100,x_100,y_100"; ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process)); WriteToFile(localImageFilename , ossObject.Content); // 将图片旋转90°。 process = "image/rotate,90"; ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process)); WriteToFile(localImageFilename , ossObject.Content); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } } private static void WriteToFile(string filePath, Stream stream) { using (var requestStream = stream) { using (var fs = File.Open(filePath, FileMode.OpenOrCreate)) { IoUtils.WriteTo(stream, fs); } } } } }
- 使用多个图片处理参数处理图片并保存为本地图片 - 使用多个图片处理参数处理图片时,多个参数之间以正斜线(/)分隔。 - using System; using System.IO; using Aliyun.OSS; using Aliyun.OSS.Common; using Aliyun.OSS.Util; namespace ImageProcessCascade { class Program { static void Main(string[] args) { Program.ImageProcessCascade(); Console.ReadKey(); } public static void ImageProcessCascade() { // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。 var endpoint = "https://oss-cn-hangzhou.aliyuncs.com"; // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET"); // 指定原图所在的Bucket名称,例如examplebucket。 var bucketName = "examplebucket"; // 指定原图名称。如果图片不在Bucket根目录,需携带图片完整路径,例如exampledir/example.jpg。 var objectName = "exampledir/example.jpg"; // 指定原图所在的本地完整路径。 var localImageFilename = "D:\\localpath\\example.jpg"; // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。 const string region = "cn-hangzhou"; // 创建ClientConfiguration实例,按照您的需要修改默认参数。 var conf = new ClientConfiguration(); // 设置v4签名。 conf.SignatureVersion = SignatureVersion.V4; // 创建OssClient实例。 var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf); client.SetRegion(region); try { // 如果原图不在目标Bucket内,需上传该图片到目标Bucket。 // client.PutObject(bucketName, objectName, localImageFilename); // 将图片缩放为固定宽高100 px后,再旋转90°。 var process = "image/resize,m_fixed,w_100,h_100/rotate,90"; var ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process)); // 指定处理后的图片名称。 WriteToFile(localImageFilename, ossObject.Content); Console.WriteLine("Get Object:{0} with process:{1} succeeded ", objectName, process); } catch (OssException ex) { Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}", ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId); } catch (Exception ex) { Console.WriteLine("Failed with error info: {0}", ex.Message); } } private static void WriteToFile(string filePath, Stream stream) { using (var requestStream = stream) { using (var fs = File.Open(filePath, FileMode.OpenOrCreate)) { IoUtils.WriteTo(stream, fs); } } } } }
使用图片样式处理图片
您可以将多个图片处理参数封装在一个样式中,之后使用样式批量处理图片。更多信息,请参见图片样式。以下代码展示了使用图片样式处理图片:
using System;
using System.IO;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using Aliyun.OSS.Util;
namespace ImageProcessCustom
{
    class Program
    {
        static void Main(string[] args)
        {
            Program.ImageProcessCustomStyle();
            Console.ReadKey();
        }
        public static void ImageProcessCustomStyle()
        {
            // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            var endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
            // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 
            var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
            var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
            // 指定原图所在的Bucket名称,例如examplebucket。
            var bucketName = "examplebucket";
            // 指定原图名称。如果图片不在Bucket根目录,需携带图片完整路径,例如exampledir/example.jpg。
            var objectName = "exampledir/example.jpg";
            // 指定原图所在的本地完整路径。
            var localImageFilename = "D:\\localpath\\example.jpg";
            // 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
            const string region = "cn-hangzhou";
            
            // 创建ClientConfiguration实例,按照您的需要修改默认参数。
            var conf = new ClientConfiguration();
            
            // 设置v4签名。
            conf.SignatureVersion = SignatureVersion.V4;
            
            // 创建OssClient实例。
            var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
            client.SetRegion(region);
            try
            {
                // 如果原图不在目标Bucket内,需上传该图片到目标Bucket。   
                // client.PutObject(bucketName, objectName, localImageFilename);
                // 使用图片样式处理图片。其中,yourCustomStyleName填写通过OSS管理控制台创建的图片样式名称。
                var process = "style/yourCustomStyleName";
                var ossObject = client.GetObject(new GetObjectRequest(bucketName, objectName, process));
                // 指定处理后的图片名称。            
                WriteToFile(localImageFilename, ossObject.Content);
                Console.WriteLine("Get Object:{0} with process:{1} succeeded ", objectName, process);
            }
            catch (OssException ex)
            {
                Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
                    ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Failed with error info: {0}", ex.Message);
            }
        }
        private static void WriteToFile(string filePath, Stream stream)
        {
            using (var requestStream = stream)
            {
                using (var fs = File.Open(filePath, FileMode.OpenOrCreate))
                {
                    IoUtils.WriteTo(stream, fs);
                }
            }
        }
    }
}生成带图片处理参数的文件签名URL
私有文件的访问URL带有签名。OSS不支持在带签名的URL后直接添加图片处理参数。如果您想要对私有文件进行图片处理,需要将图片处理参数加入到签名中,相关的代码示例如下:
using Aliyun.OSS;
using Aliyun.OSS.Common;
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
var endpoint = "yourEndpoint";
// 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。 
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID"); 
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// 指定图片所在Bucket的名称,例如examplebucket。
var bucketName = "examplebucket";
// 指定图片名称。如果图片不在Bucket根目录,需携带文件完整路径,例如exampledir/example.jpg。
var objectName = "exampledir/exampledir.jpg";
// 填写Bucket所在地域对应的Region。以华东1(杭州)为例,Region填写为cn-hangzhou。
const string region = "cn-hangzhou";
// 创建ClientConfiguration实例,按照您的需要修改默认参数。
var conf = new ClientConfiguration();
// 设置v4签名。
conf.SignatureVersion = SignatureVersion.V4;
// 创建OssClient实例。
var client = new OssClient(endpoint, accessKeyId, accessKeySecret, conf);
client.SetRegion(region);
try
{
    // 将图片缩放为固定宽高100 px。
    var process = "image/resize,m_fixed,w_100,h_100";
    var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
    {
        Expiration = DateTime.Now.AddHours(1),
        Process = process
    };
    // 生成带有签名的URI。
    var uri = client.GeneratePresignedUri(req);
    Console.WriteLine("Generate Presigned Uri:{0} with process:{1} succeeded ", uri, process);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}图片处理工具
您可以通过可视化图片处理工具ImageStyleViewer直观地看到OSS图片处理结果。
相关文档
该文章对您有帮助吗?