简体   繁体   English

相同的图像调整大小和图像裁剪功能可在Winforms应用程序中使用,而在相同解决方案的Webapi应用程序中则无法使用

[英]Same image resize and image crop functionality works in a Winforms app, and doesn't work in a Webapi app of the same solution

Short intro: I have this solution which consists of a Webapi app, Winforms (UI) app, then Xamarin Forms (Android, UWP, iOS). 简短介绍:我有一个由Webapi应用,Winforms(UI)应用,然后是Xamarin Forms(Android,UWP,iOS)组成的解决方案。

Now, resize and crop functionality works in Winforms' app. 现在,调整大小和裁剪功能可以在Winforms的应用程序中使用。 Since I'm using in my Webapi app PerformInitSetup() to init the data, I also wanted to apply here the functionality of thumbnail generation. 由于我在Webapi应用中使用PerformInitSetup()初始化数据,因此我还想在此处应用缩略图生成功能。

These are the methods (which are placed in a helper class of each app): 这些是方法(放置在每个应用程序的帮助器类中):

    public static Image CropImage(Image img, Rectangle cropArea)
    {
        Bitmap bmpImage = new Bitmap(img);
        Bitmap bmpCrop = bmpImage.Clone(cropArea,
        bmpImage.PixelFormat);
        return (Image)(bmpCrop);
    }

    public static Image ResizeImage(Image imgToResize, Size size)
    {
        int sourceWidth = imgToResize.Width;
        int sourceHeight = imgToResize.Height;

        float nPercent = 0;
        float nPercentW = 0;
        float nPercentH = 0;

        nPercentW = ((float)size.Width / (float)sourceWidth);
        nPercentH = ((float)size.Height / (float)sourceHeight);

        if (nPercentH < nPercentW)
            nPercent = nPercentH;
        else
            nPercent = nPercentW;

        int destWidth = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        Bitmap b = new Bitmap(destWidth, destHeight);
        Graphics g = Graphics.FromImage((Image)b);
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
        g.Dispose();

        return (Image)b;
    }

In Winforms app (which does work), here's how a regular image is saved, and then a thumbnail generated based on it: 在Winforms应用程序中(有效),以下是常规图像的保存方式,然后基于该图像生成缩略图:

    private void btnAddImage_Click(object sender, EventArgs e)
    {
        if (openFileDialog.ShowDialog() == DialogResult.OK)
        {
            txtImage.Text = openFileDialog.FileName;
            Image originalImage = Image.FromFile(openFileDialog.FileName);

            MemoryStream ms = new MemoryStream();
            originalImage.Save(ms, ImageFormat.Jpeg);

            lodging.Image = ms.ToArray();


            int resizedImageWidth = Convert.ToInt32(ConfigurationManager.AppSettings["resizedImageWidth"]);
            int resizedImageHeight = Convert.ToInt32(ConfigurationManager.AppSettings["resizedImageHeight"]);
            int croppedImageWidth = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImageWidth"]);
            int croppedImageHeight = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImageHeight"]);

            if(originalImage.Width > resizedImageWidth)
            {
                Image resizedImage = Util.UIHelper.ResizeImage(originalImage, new Size(resizedImageWidth, resizedImageHeight));
                Image croppedImage = resizedImage;

                if(resizedImage.Width >= croppedImageWidth && resizedImage.Height >= croppedImageHeight)
                {
                    int croppedXPos = (resizedImageWidth - croppedImageWidth) / 2;
                    int croppedYPos = (resizedImageHeight - croppedImageHeight) / 2;

                    croppedImage = Util.UIHelper.CropImage(resizedImage, new Rectangle(croppedXPos, croppedYPos, croppedImageWidth, croppedImageHeight));

                    ms = new MemoryStream();
                    croppedImage.Save(ms, ImageFormat.Jpeg);
                    lodging.ImageThumb = ms.ToArray();

                }
            }
        }
    }

So far, so good. 到现在为止还挺好。

But when I tried to do the same in Webapi app's PerformInitSetup() method, I'm getting an error (find it at the bottom): 但是,当我尝试在Webapi应用的PerformInitSetup()方法中执行相同操作时,出现了错误(在底部找到):

// ... other init data

MemoryStream ms1 = new MemoryStream();
Image img1 = Image.FromFile("D:\\Path\\To\\MyImage\\image.jpg");
img1.Save(ms1, ImageFormat.Jpeg);

MemoryStream img1Thumb = GenerateThumbnailImage(img1);

_ctx.LodgingDbSet.Add(new Lodging { Name = "Name Name", ... other attributes ... , Image = ms1.ToArray(), ImageThumb = img1Thumb.ToArray(), CityId = 1, UserId = 2 });

// ... other init data

Within the class InitDB : DropCreateDatabaseIfModelChanges<MyDbContext> , where PerformInitSetup() method is, I have: 在类InitDB : DropCreateDatabaseIfModelChanges<MyDbContext> ,其中PerformInitSetup()方法在其中,我有:

    private MemoryStream GenerateThumbnailImage(Image originalImage)
    {
        int resizedImageWidth = Convert.ToInt32(ConfigurationManager.AppSettings["resizedImageWidth"]);
        int resizedImageHeight = Convert.ToInt32(ConfigurationManager.AppSettings["resizedImageHeight"]);
        int croppedImageWidth = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImageWidth"]);
        int croppedImageHeight = Convert.ToInt32(ConfigurationManager.AppSettings["croppedImageHeight"]);

        MemoryStream ms = new MemoryStream();

        if (originalImage.Width > resizedImageWidth)
        {
            Image resizedImage = Util.Helper.ResizeImage(originalImage, new Size(resizedImageWidth, resizedImageHeight));
            Image croppedImage = resizedImage;

            if (resizedImage.Width >= croppedImageWidth && resizedImage.Height >= croppedImageHeight)
            {
                int croppedXPos = (resizedImageWidth - croppedImageWidth) / 2;
                int croppedYPos = (resizedImageHeight - croppedImageHeight) / 2;

                croppedImage = Util.Helper.CropImage(
                    resizedImage,
                    new Rectangle(croppedXPos, croppedYPos, croppedImageWidth, croppedImageHeight)
                    );

                croppedImage.Save(ms, ImageFormat.Jpeg);
            }
        }

        return ms;
    }

I thought it would work. 我以为这样可以。 However, something is wrong, but unfortunately, for some reason, breakpoints seem to not be working within this MyDbContext file (explanation thereof would be appreciated!), so I'm getting this error: 但是,出了点问题,但是不幸的是,由于某种原因,断点似乎无法在此MyDbContext文件中工作( MyDbContext !),所以出现了此错误:

{"Message":
"An error has occurred.",
"ExceptionMessage":
    "Parameter is not valid.",
"ExceptionType":"System.ArgumentException",

"StackTrace":
"   at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)\r\n
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)\r\n
at My_API.Util.Helper.ResizeImage(Image imgToResize, Size size) in D:\\Path\\To\\MyApp\\My_API\\Util\\Helper.cs:line 42\r\n
at My_API.DAL.InitDb.GenerateThumbnailImage(Image originalImage) in D:\\Path\\To\\MyApp\\My_API\\DAL\\MyDbContext.cs:line 341\r\n
at My_API.DAL.InitDb.PerformInitSetup(MyDbContext _ctx) in D:\\Path\\To\\MyApp\\My_API\\DAL\\MyDbContext.cs:line 176\r\n
at My_API.DAL.InitDb.Seed(MyDbContext _ctx) in D:\\Path\\To\\MyApp\\My_API\\DAL\\MyDbContext.cs:line 67\r\n
at System.Data.Entity.DropCreateDatabaseIfModelChanges`1.InitializeDatabase(TContext context)\r\n
// ... more stuff follows

It seems like the passed Image object to the above method is not correct. 似乎传递给上述方法的Image对象不正确。 However, IMO, it is the same as in working Winforms app example. 但是,IMO与工作于Winforms应用程序示例中的相同。

Am I missing something obvious? 我是否缺少明显的东西?

Edit: As suggested in a comment, I'm also providing contents of my Web.config: 编辑:如评论中所建议,我还提供了Web.config的内容:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="MyConnString" connectionString="Data Source=(local);Initial Catalog=mycatalog;Integrated Security=SSPI;MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <appSettings></appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
  </system.web>
  <system.webServer>
    <handlers>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.7.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
</configuration>

The most likely cause is that you have not defined these settings in your web.config : 最可能的原因是您尚未在web.config定义以下设置:

resizedImageWidth
resizedImageHeight
croppedImageWidth
croppedImageHeight

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM