Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/273.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法调整上载到Dot NET Lambda函数项目中s3存储桶的图像大小_C#_Amazon Web Services_Amazon S3_.net Core_Aws Lambda - Fatal编程技术网

C# 无法调整上载到Dot NET Lambda函数项目中s3存储桶的图像大小

C# 无法调整上载到Dot NET Lambda函数项目中s3存储桶的图像大小,c#,amazon-web-services,amazon-s3,.net-core,aws-lambda,C#,Amazon Web Services,Amazon S3,.net Core,Aws Lambda,我正在使用C#NET内核开发一个AWS Lambda函数项目。我现在正在做的是,当图像文件上传到s3时,我正在调整图像的大小。这是我的项目结构 我在单一解决方案中有三个项目。域项目是Dot-NET框架项目,而AwsLambda是Dot-NET核心项目。Aws Lambda项目依赖于AwsLambda.Domain项目。基本上,在AwsLambda.Domain项目中,我创建了一个名为ImageHelper.cs的新类,该类负责使用来自Dot NET框架的功能调整图像大小 { "errorT

我正在使用C#NET内核开发一个AWS Lambda函数项目。我现在正在做的是,当图像文件上传到s3时,我正在调整图像的大小。这是我的项目结构

我在单一解决方案中有三个项目。域项目是Dot-NET框架项目,而AwsLambda是Dot-NET核心项目。Aws Lambda项目依赖于AwsLambda.Domain项目。基本上,在AwsLambda.Domain项目中,我创建了一个名为ImageHelper.cs的新类,该类负责使用来自Dot NET框架的功能调整图像大小

{
  "errorType": "AggregateException",
  "errorMessage": "One or more errors occurred. (Could not load type 'System.Drawing.Image' from assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.)",
  "stackTrace": [
    "at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)",
    "at lambda_method(Closure , Stream , Stream , LambdaContextInternal )"
  ],
  "cause": {
    "errorType": "TypeLoadException",
    "errorMessage": "Could not load type 'System.Drawing.Image' from assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.",
    "stackTrace": [
      "at AwsS3Lambda.Domain.ImageHelper.CreateThumbImage(String sourcePath, String destPath, Int32 width, Int32 height)",
      "at AwsS3Lambda.Function.<FunctionHandler>d__18.MoveNext() in C:\\Users\\Acer\\Documents\\Visual Studio 2017\\Projects\\AwsS3Lambda\\AwsS3Lambda\\Function.cs:line 106"
    ]
  },
  "causes": [
    {
      "errorType": "TypeLoadException",
      "errorMessage": "Could not load type 'System.Drawing.Image' from assembly 'System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.",
      "stackTrace": [
        "at AwsS3Lambda.Domain.ImageHelper.CreateThumbImage(String sourcePath, String destPath, Int32 width, Int32 height)",
        "at AwsS3Lambda.Function.<FunctionHandler>d__18.MoveNext() in C:\\Users\\Acer\\Documents\\Visual Studio 2017\\Projects\\AwsS3Lambda\\AwsS3Lambda\\Function.cs:line 106"
      ]
    }
  ]
}
这是AwsLambda.Doamin项目下的ImageHelper.cs类

using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;

namespace AwsS3Lambda.Domain
{
   public class ImageHelper
   {
      public string CreateThumbImage(string sourcePath, string destPath, int width, int height)
      {
         Image imgOriginal = Image.FromFile(sourcePath);
         Image imgActual = Scale(imgOriginal, width, height);
         imgActual.Save(destPath);
         imgActual.Dispose();
         return destPath;
      }


      private Image Scale(Image imgPhoto, int width, int height)
      {
         float sourceWidth = imgPhoto.Width;
         float sourceHeight = imgPhoto.Height;
         float destHeight = 0;
         float destWidth = 0;
         int sourceX = 0;
         int sourceY = 0;
         int destX = 0;
         int destY = 0;

         // force resize, might distort image
         if(width != 0 && height != 0)
         {
            destWidth = width;
            destHeight = height;
         }
         // change size proportially depending on width or height
         else if(height != 0)
         {
            destWidth = (float)(height * sourceWidth) / sourceHeight;
            destHeight = height;
         }
         else
         {
            destWidth = width;
            destHeight = (float)(sourceHeight * width / sourceWidth);
         }

         Bitmap bmPhoto = new Bitmap((int)destWidth, (int)destHeight,
                                     PixelFormat.Format32bppPArgb);
         bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

         Graphics grPhoto = Graphics.FromImage(bmPhoto);
         grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

         grPhoto.DrawImage(imgPhoto,
             new Rectangle(destX, destY, (int)destWidth, (int)destHeight),
             new Rectangle(sourceX, sourceY, (int)sourceWidth, (int)sourceHeight),
             GraphicsUnit.Pixel);

         grPhoto.Dispose();

         return bmPhoto;
      }
   }
}
这是我的lambda函数类,它使用ImageHelper.cs类调整上载图像的大小

 public class Function
    {
      public static string IAM_KEY { get { return "xxx"; } }
      public static string IAM_SECRET { get { return "xxx"; } }
      public static string TEMP_IMG_FILE_PATH { get { return @"../../tmp/temp_img.jpeg"; } }
      public static string TEMP_RESIZED_IMG_PATH { get { return @"../../tmp/resized_img.jpeg"; } }

      private IAmazonS3 S3Client { get; set; }
      private ImageHelper imageHelper { get; set; }


      public Function()
      {
         S3Client = new AmazonS3Client();
         imageHelper = new ImageHelper();
      }


      public Function(IAmazonS3 s3Client)
      {
         this.S3Client = s3Client;
         this.imageHelper = new ImageHelper();
      }

      public async Task<string> FunctionHandler(S3Event evnt, ILambdaContext context)
      {
         var s3Event = evnt.Records?[0].S3;
         if(s3Event == null)
         {
            return null;
         }

         try
         {
            if(s3Event.Object.Key.ToLower().Contains("thumb"))
            {
               //Console.WriteLine("The image is already a thumb file");
               return "The file is aready a thumb image file";
            }

            string[] pathSegments = s3Event.Object.Key.Split('/');
            string eventCode = pathSegments[0];
            string userEmail = pathSegments[1];
            string filename = pathSegments[2];
            string extension = Path.GetExtension(filename); //.jpeg with "dot"
            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filename);

            using(var objectResponse = await this.S3Client.GetObjectAsync(s3Event.Bucket.Name, s3Event.Object.Key))
            {
               using(Stream responseStream = objectResponse.ResponseStream)
               {
                  this.saveFile(responseStream, Function.TEMP_IMG_FILE_PATH);

                  imageHelper.CreateThumbImage(Function.TEMP_IMG_FILE_PATH, Function.TEMP_RESIZED_IMG_PATH, 200, 200);

                  ///This code is throwing error
                  await this.S3Client.PutObjectAsync(new Amazon.S3.Model.PutObjectRequest
                  {
                     BucketName = s3Event.Bucket.Name,
                     Key = fileNameWithoutExtension + ".thumb" + extension,
                     FilePath = Function.TEMP_RESIZED_IMG_PATH
                  });
               }
            }

            return "Thumbnail version of the image has been created";

         }
         catch(Exception e)
         {
            context.Logger.LogLine($"Error getting object {s3Event.Object.Key} from bucket {s3Event.Bucket.Name}. Make sure they exist and your bucket is in the same region as this function.");
            context.Logger.LogLine(e.Message);
            context.Logger.LogLine(e.StackTrace);
            throw;
         }
      }

      private void saveFile(Stream stream, string path)
      {
         using(var fileStream = File.Create(path))
         {
            //stream.Seek(0, SeekOrigin.Begin);
            stream.CopyTo(fileStream);
         }

      }
   }
公共类函数
{
公共静态字符串IAM_KEY{get{返回“xxx”;}
公共静态字符串IAM_SECRET{get{返回“xxx”;}
公共静态字符串TEMP_IMG_FILE_PATH{get{return@./../tmp/TEMP_IMG.jpeg”;}
公共静态字符串TEMP_RESIZED_IMG_PATH{get{return@./../tmp/RESIZED_IMG.jpeg”;}
私有IAmazonS3客户端{get;set;}
私有ImageHelper ImageHelper{get;set;}
公共职能()
{
S3Client=新的AmazonS3Client();
imageHelper=新的imageHelper();
}
公共功能(IAmazonS3客户端)
{
this.S3Client=S3Client;
this.imageHelper=新的imageHelper();
}
公共异步任务FunctionHandler(S3Event evnt,ILambdaContext上下文)
{
var s3Event=evnt.Records?[0].S3;
if(s3Event==null)
{
返回null;
}
尝试
{
if(s3Event.Object.Key.ToLower()包含(“thumb”))
{
//WriteLine(“图像已经是一个拇指文件”);
返回“该文件是一个拇指图像文件”;
}
string[]pathSegments=s3Event.Object.Key.Split('/');
字符串eventCode=pathSegments[0];
字符串userEmail=pathSegments[1];
字符串文件名=路径段[2];
字符串扩展名=Path.GetExtension(文件名);//.jpeg,带“点”
字符串fileNameWithoutExtension=Path.GetFileNameWithoutExtension(文件名);
使用(var objectResponse=wait this.S3Client.GetObjectAsync(s3Event.Bucket.Name,s3Event.Object.Key))
{
使用(Stream responseStream=objectResponse.responseStream)
{
这个.saveFile(responseStream,Function.TEMP\u IMG\u FILE\u路径);
CreateThumbImage(Function.TEMP\u IMG\u FILE\u PATH,Function.TEMP\u RESIZED\u IMG\u PATH,200200);
///此代码正在抛出错误
等待这个.S3Client.PutObjectAsync(新的Amazon.S3.Model.PutObjectRequest
{
BucketName=s3Event.Bucket.Name,
Key=filename不带outextension+“.thumb”+扩展名,
FilePath=Function.TEMP\u大小调整的\u IMG\u路径
});
}
}
返回“已创建图像的缩略图版本”;
}
捕获(例外e)
{
context.Logger.LogLine($“从bucket{s3Event.bucket.Name}获取对象{s3Event.object.Key}时出错。请确保它们存在并且您的bucket与此函数位于同一区域。”);
context.Logger.LogLine(e.Message);
context.Logger.LogLine(如StackTrace);
投掷;
}
}
私有void保存文件(流、字符串路径)
{
使用(var fileStream=File.Create(path))
{
//stream.Seek(0,SeekOrigin.Begin);
CopyTo(fileStream);
}
}
}
当我在控制台中测试该函数时,它给了我一个关于在AwsLambda.Domain项目(dotnetframework)下实现的图像大小调整功能的错误

{
“errorType”:“AggregateException”,
“errorMessage”:“出现一个或多个错误。(无法加载类型“System.Drawing.Image”“from assembly”System.Drawing,版本=4.0.0.0,区域性=中性,PublicKeyToken=b03f5f7f11d50a3a”。”,
“stackTrace”:[
“位于System.Threading.Tasks.Task`1.GetResultCore(布尔waitCompletionNotification)”,
“在lambda_方法(闭包、流、流、lambdacontexternal)”
],
“原因”:{
“errorType”:“TypeLoadException”,
“errorMessage:“无法从程序集”“System.Drawing”“加载类型”“System.Drawing.Image”“,版本=4.0.0.0,区域性=中性,PublicKeyToken=b03f5f7f11d50a3a”“。”,
“stackTrace”:[
“在AwsS3Lambda.Domain.ImageHelper.CreateTumbImage(字符串sourcePath、字符串destPath、Int32 width、Int32 height)”中,
“在C:\\Users\\Acer\\Documents\\Visual Studio 2017\\Project\\AwsS3Lambda\\AwsS3Lambda\\Function.d_u18.MoveNext()中
]
},
“原因”:[
{
“errorType”:“TypeLoadException”,
“errorMessage:“无法从程序集”“System.Drawing”“加载类型”“System.Drawing.Image”“,版本=4.0.0.0,区域性=中性,PublicKeyToken=b03f5f7f11d50a3a”“。”,
“stackTrace”:[
“在AwsS3Lambda.Domain.ImageHelper.CreateTumbImage(字符串sourcePath、字符串destPath、Int32 width、Int32 height)”中,
“在C:\\Users\\Acer\\Documents\\Visual Studio 2017\\Project\\AwsS3Lambda\\AwsS3Lambda\\Function.d_u18.MoveNext()中
]
}
]
}

为什么会犯这样的错误。当我在ASP.NET MVC项目中使用图像大小调整类代码时,它正在工作。它只是不适用于这个AWS Lambda函数项目。我的项目缺少什么?在AWS Lambda功能项目中,如果要调整上传图像的大小,另一种方法是什么?该项目基于Dot NET Core

在Amazon上,您只能使用.NETC