【问题标题】:How to fix Generic GDI+ error when saving/uploading an image?保存/上传图像时如何修复通用 GDI+ 错误?
【发布时间】:2021-07-08 07:21:00
【问题描述】:

您好,我的代码有问题,我尝试制作一个编辑器,让您能够上传图片并让您裁剪它,但是在将图片上传到系统时出现问题,当我在 locahost 中运行它时,它没有问题它可以上传,一切都很好,但是当我必须从域上传图像时,它给了我这个错误,我尝试使用 .dispose();但它没有解决可能在错误的地方使用,Jpg,png等。什么都不能上传。请帮帮我..

还有一个问题,当我尝试使用 Visual Studio Publish(FTP) 将我的项目上传到域时,我不知道它是否与我的主要问题有关,它没有将我的 img 文件夹放入FTP,我必须从 FileZilla 手动创建它

This my GDI+ Error

This is my Solution explorer

这是我做所有事情的代码

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FancyImageUploader.Models;
using System.Drawing;
using System.IO;
using System.Drawing.Drawing2D;
using System.Net;

namespace FancyImageUploader.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/Index

        public ActionResult Index()
        {
            var images = new ImagesModel();
            //Read out files from the files directory
            var files = Directory.GetFiles(Server.MapPath("~/Content/img/"));
            //Add them to the model
            foreach (var file in files)
                images.Images.Add(Path.GetFileName(file));

            return View(images);
        }

        //
        // GET: /Home/UploadImage

        public ActionResult UploadImage()
        {
            return View();
        }

        //
        // POST: /Home/UploadImage

        [HttpPost]
        public ActionResult UploadImage(UploadImageModel model)
        {
            //Check if all simple data annotations are valid
            if (ModelState.IsValid)
            {
                //Prepare the needed variables
                Bitmap original = null;
                var name = "newimagefile";
                var errorField = string.Empty;


                if (model.IsUrl)
                {
                    errorField = "Url";
                    name = GetUrlFileName(model.Url);
                    original = GetImageFromUrl(model.Url);
                }
                else if (model.IsFlickr)
                {
                    errorField = "Flickr";
                    name = GetUrlFileName(model.Flickr);
                    original = GetImageFromUrl(model.Flickr);
                }
                else if (model.File != null) // model.IsFile
                {
                    errorField = "File";
                    name = Path.GetFileNameWithoutExtension(model.File.FileName);
                    original = Bitmap.FromStream(model.File.InputStream) as Bitmap;
                }

                //If we had success so far
                if (original != null)
                {
                    var img = CreateImage(original, model.X, model.Y, model.Width, model.Height);

                    //Demo purposes only - save image in the file system
                    var fn = Server.MapPath("~/Content/img/" + name + ".png");
                    img.Save(fn, System.Drawing.Imaging.ImageFormat.Png);

                    //Redirect to index
                    return RedirectToAction("Index");
                }
                else //Otherwise we add an error and return to the (previous) view with the model data
                    ModelState.AddModelError(errorField, "Your upload did not seem valid. Please try again using only correct images!");
            }

            return View(model);
            
        }

        /// <summary>
        /// Gets an image from the specified URL.
        /// </summary>
        /// <param name="url">The URL containing an image.</param>
        /// <returns>The 
        Bitmap GetImageFromUrl(string url)
        {
            var buffer = 1024;
            Bitmap image = null;

            if (!Uri.IsWellFormedUriString(url, UriKind.Absolute))
                return image;

            using (var ms = new MemoryStream())
            {
                var req = WebRequest.Create(url);

                using (var resp = req.GetResponse())
                {
                    using (var stream = resp.GetResponseStream())
                    {
                        var bytes = new byte[buffer];
                        var n = 0;

                        while ((n = stream.Read(bytes, 0, buffer)) != 0)
                            ms.Write(bytes, 0, n);
                    }
                }

                image = Bitmap.FromStream(ms) as Bitmap;
            }

            return image;
        }

        /// <summary>
        /// Gets the filename that is placed under a certain URL.
        /// </summary>
        /// <param name="url">The URL which should be investigated for a file name.</param>
        /// <returns>The file name.</returns>
        string GetUrlFileName(string url)
        {
            var parts = url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            var last = parts[parts.Length - 1];
            return Path.GetFileNameWithoutExtension(last);
        }

        /// <summary>
        /// Creates a small image out of a larger image.
        /// </summary>
        /// <param name="original">The original image which should be cropped (will remain untouched).</param>
        /// <param name="x">The value where to start on the x axis.</param>
        /// <param name="y">The value where to start on the y axis.</param>
        /// <param name="width">The width of the final image.</param>
        /// <param name="height">The height of the final image.</param>
        /// <returns>The cropped image.</returns>
        Bitmap CreateImage(Bitmap original, int x, int y, int width, int height)
        {
            var img = new Bitmap(width, height);

            using (var g = Graphics.FromImage(img))
            {
                g.SmoothingMode = SmoothingMode.AntiAlias;
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.DrawImage(original, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
            }

            return img;
        }
    }
}

这是我的 cshtml 与 HomeController 配合使用

@using Deneme.Source
@model FancyImageUploader.Models.UploadImageModel
@{
    ViewBag.Title = "Image uploader";
}
@section Styles
{
<link href="@Url.Content("~/Content/ImageArea.css")" rel="stylesheet" />
}
@section Scripts
{
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"></script>
<script src="@Url.Content("~/Scripts/jquery.imgareaselect.js")"></script>
<script>
    $(document).ready(function () {
        //Get the checkboxes and disable them
        var boxes = $('input[type=checkbox]').attr('disabled', true);

        //Get the preview image and set the onload event handler
        var preview = $('#preview').load(function () {
            setPreview();
            ias.setOptions({
                x1: 0,
                y1: 0,
                x2: $(this).width(),
                y2: $(this).height(),
                show: true
            });
        });

        //Set the 4 coordinates for the cropping
        var setPreview = function (x, y, w, h) {
            $('#X').val(x || 0);
            $('#Y').val(y || 0);
            $('#Width').val(w || preview[0].naturalWidth);
            $('#Height').val(h || preview[0].naturalHeight);
        };

        //Initialize the image area select plugin
        var ias = preview.imgAreaSelect({
            handles: true,
            instance: true,
            parent: 'body',
            onSelectEnd: function (s, e) {
                var scale = preview[0].naturalWidth / preview.width();
                var _f = Math.floor;
                setPreview(_f(scale * e.x1), _f(scale * e.y1), _f(scale * e.width), _f(scale * e.height));
            }
        });

        //Check one of the checkboxes
        var setBox = function (filter) {
            $('button').attr('disabled', false);
            boxes.attr('checked', false)
            .filter(filter).attr({ 'checked': true, 'disabled': false });
        };

        //Initial state of X, Y, Width and Height is 0 0 1 1
        setPreview(0, 0, 1, 1);

        //Fetch Flickr images
        var fetchImages = function (query) {
            $.getJSON('http://www.flickr.com/services/feeds/photos_public.gne?jsoncallback=?', {
                tags: query,
                tagmode: "any",
                format: "json"
            }, function (data) {
                var screen = $('<div />').addClass('waitScreen').click(function () {
                    $(this).remove();
                }).appendTo('body');
                var box = $('<div />').addClass('flickrImages').appendTo(screen);
                $.each(data.items, function (i, v) {
                    console.log(data.items[i]);
                    $('<img />').addClass('flickrImage').attr('src', data.items[i].media.m).click(function () {
                        $('#Flickr').val(this.src).change();
                        screen.remove();
                    }).appendTo(box);
                });
            });
        };

        //Flickr
        $('#FlickrQuery').change(function () {
            fetchImages(this.value);
        });

        $('#Flickr').change(function () {
            setBox('#IsFlickr');
            preview.attr('src', this.value);
        });

        //What happens if the URL changes?
        $('#Url').change(function () {
            setBox('#IsUrl');
            preview.attr('src', this.value);
        });

        //What happens if the File changes?
        $('#File').change(function (evt) {
            var f = evt.target.files[0];
            var reader = new FileReader();

            if (!f.type.match('image.*')) {
                alert("The selected file does not appear to be an image.");
                return;
            }

            setBox('#IsFile');
            reader.onload = function (e) { preview.attr('src', e.target.result); };
            reader.readAsDataURL(f);
        });

        //What happens if any checkbox is checked ?!
        boxes.change(function () {
            setBox(this);
            $('#' + this.id.substr(2)).change();
        });

        $('button').attr('disabled', true);
        $('form').submit(function () {
            $('button').attr('disabled', true).text('Please wait ...');
        });
    });
</script>
}
<h2>Upload an image</h2>
@using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.HiddenFor(model => model.X)
    @Html.HiddenFor(model => model.Y)
    @Html.HiddenFor(model => model.Width)
    @Html.HiddenFor(model => model.Height)
    @Html.HiddenFor(model => model.Flickr)
    <div id="upload-choices">
        <div class="editor-row">
            <div class="editor-label">
                @Html.EditorFor(model => model.IsUrl)
                @Html.LabelFor(model => model.Url)
            </div><div class="editor-field">
                @Html.EditorFor(model => model.Url)
                @Html.ValidationMessageFor(model => model.Url)
            </div>
        </div>
        <div class="editor-row">
            <div class="editor-label">
                @Html.EditorFor(model => model.IsFlickr)
                @Html.LabelFor(model => model.Flickr)
            </div><div class="editor-field">
                @Html.Editor("FlickrQuery")
                @Html.ValidationMessageFor(model => model.Flickr)
            </div>
        </div>
        <div class="editor-row">
            <div class="editor-label">
                @Html.EditorFor(model => model.IsFile)
                @Html.LabelFor(model => model.File)
            </div><div class="editor-field">
                @Html.FileFor(model => model.File)
                @Html.ValidationMessageFor(model => model.File)
            </div>
        </div>
        <div class="editor-row">
            @Html.ValidationSummary(true)
        </div>
    </div>
    <div id="upload-cut">
        <img alt="Field for image cutting" id="preview" src="@Url.Content("~/Content/empty.png")" />
    </div>
    <div class="clear">
        <button type="submit">Upload</button>
    </div>
}

【问题讨论】:

  • 强烈建议不要在asp.net应用程序中使用Image/Bitmap。官方不支持,since it uses unmanaged resources in the server's GDI+ system“System.Drawing 命名空间中的某些类型依赖于 GDI+,这在 Windows 服务和 ASP.NET Core 和 ASP.NET 应用程序中不受支持。”该注意事项,您应该处置 img(或者,更好的是,将其放在 using 块中)以确保释放系统资源。

标签: c# model-view-controller razor gdi+


【解决方案1】:

我发现是FTP文件权限问题,修复了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-07
    • 2011-06-21
    • 2017-08-18
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    相关资源
    最近更新 更多