2017-09-09 12 views
1

短い紹介: 私はWebapiアプリ、Winforms(UI)アプリ、次にXamarinフォーム(Android、UWP、iOS)同じイメージリサイズとイメージクロップ機能は、Winformsアプリケーションで動作し、同じソリューションのWebapiアプリケーションでは機能しません。

今、サイズ変更とクロップ機能はWinformsのアプリケーションで動作します。私は私のWebapiアプリケーションPerformInitSetup()でデータを初期化するために使用しているので、ここでもサムネイル生成の機能を適用したいと思っていました。

これらは、(各アプリのヘルパークラスに配置されている)メソッドです。(仕事をする)のWinFormsアプリで

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; 
    } 

、ここでは定期的に画像が保存されている方法です、その後、サムネイルが生成されそれに基づいて:

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(); 

       } 
      } 
     } 
    } 

これまでのところ、とても良いです。

しかし、私はWEBAPIアプリのPerformInitSetup()方法で同じことをしようとしたとき、私はエラー(下でそれを見つける)取得しています:PerformInitSetup()メソッドがあるクラスInitDB : DropCreateDatabaseIfModelChanges<MyDbContext>、内

// ... 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 

を、I持っています:

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; 
    } 

私はそれがうまくいくと思いました。しかし、何かが間違っているが、残念ながら、何らかの理由で、ブレークポイントは、(その説明は理解されるだろう!)ので、私はこのエラーを取得しています。この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 

それはのように思えます上記の方法に渡されたImageオブジェクトは正しくありません。しかし、IMOは、それはWinformsのアプリケーションの例を動作させるのと同じです。

明らかなものがありませんか?

編集:コメントで示唆したように、私も私の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> 
+1

他のエンティティフレームワークは機能しますか?これはあなたの画像操作と関係しているように私には見えません。いくつかのハードコードされたデータを持つ最小限の例を作成して、データコンテキストに集中することができます。 – Crowcoder

+0

@Crowcoderはい、私がこのメソッドと呼ぶこの時点までの他のテーブルは作成されますが、それ以降は作成されません – developer10

+0

@mjwillsそれでした。私は無意識のうちに、コード内でエラーが発生していないので、UIアプリケーションのApp.configからこれらのコードが選択されていると考えました。彼らはそうではなかったので、私はそれらをWeb.configに入れ、それは動作します。 私はそれを受け入れるために回答を作成してください。 – developer10

答えて

0

最も可能性の高い原因は、あなたのweb.configでこれらの設定を定義していないということです。

resizedImageWidth 
resizedImageHeight 
croppedImageWidth 
croppedImageHeight 
関連する問題