1

我让图像上传工作并保存到网络服务器上的文件夹中。我需要在上传之前调整图像大小,但是如何在 ajax 控制工具包上传程序开始上传过程之前获取字节数组。我知道我必须覆盖控件,我在哪里挂钩到上传事件?提前致谢。

我有调用方法来调整大小的代码;所以我想将字节数组返回给上传事件。

在处理 Yuriy 的答案之后。

添加答案中概述的代码后,我重新编译了控制工具包。我可以将 3 个属性添加到 HtmlEditorExtender 实例。保存图像的代码驻留在 OnUploadCompleted 事件中,但不调用 HtmlEditorExtender.cs 文件中的调整大小代码。使用 JustDecomplie,我可以看到 dll 在重新编译的工具包中发生了变化。我将工具包重新添加到 VS 2012 工具箱并重新创建了对 dll 的引用。我知道我已经接近让这个新功能正常工作,但我希望另一只手帮助我让调整大小功能正常工作。

protected void ajaxFileUpload_OnUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
    if (e.ContentType.Contains("jpg") || e.ContentType.Contains("gif")
        || e.ContentType.Contains("png") || e.ContentType.Contains("jpeg"))
    {
        Session["fileContentType_" + e.FileId] = e.ContentType;
        Session["fileContents_" + e.FileId] = e.GetContents();
    }

    string fullPath = "/ExtenderImages/" + e.FileName;

    // Save your File
    HtmlEditorExtender1.AjaxFileUpload.SaveAs(Server.MapPath(fullPath));

    e.PostedUrl = fullPath;
}
4

1 回答 1

1

您需要下载 AjaxControlToolkit 源并自定义Server/AjaxControlToolkit/HtmlEditorExtender/HtmlEditorExtender.cs文件。将以下属性添加到 HtmlEditorExtender 类:

[Browsable(true)]
[DefaultValue(false)]
public bool ResizeUploadedImages { get; set; }

[Browsable(true)]
[DefaultValue(int.MaxValue)]
public int UploadedImageMaxWidth { get; set; }

[Browsable(true)]
[DefaultValue(int.MaxValue)]
public int UploadedImageMaxHeight { get; set; }

此外,修复 OnInit 方法如下:

/// <summary>
/// On Init add popup div and ajaxfileupload control to support Add image
/// </summary>
/// <param name="e">Event Arguments</param>
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    if (!DesignMode)
    {
        // Check if EnableSanitization is enabled and sanitizer provider is not configured.
        if (EnableSanitization && sanitizerProvider == null)
        {
            throw new Exception("Sanitizer provider is not configured in the web.config file. If you are using the HtmlEditorExtender with a public website then please configure a Sanitizer provider. Otherwise, set the EnableSanitization property to false.");
        }

        HtmlGenericControl popupdiv = new HtmlGenericControl("div");
        popupdiv.Attributes.Add("Id", this.ClientID + "_popupDiv");
        popupdiv.Attributes.Add("style", "opacity: 0;");
        popupdiv.Attributes.Add("class", "popupDiv");

        ajaxFileUpload = new AjaxFileUpload();
        ajaxFileUpload.ID = this.ID + "_ajaxFileUpload";
        ajaxFileUpload.MaximumNumberOfFiles = 10;
        ajaxFileUpload.AllowedFileTypes = "jpg,jpeg,gif,png";
        ajaxFileUpload.Enabled = true;
        ajaxFileUpload.OnClientUploadComplete = "ajaxClientUploadComplete";

        if(ResizeUploadedImages)
        {
            ajaxFileUpload.UploadComplete += (sender, args) =>
                                                    {
                                                        var content = args.GetContents();
                                                        var resized = ResizeImage(content, UploadedImageMaxWidth, UploadedImageMaxHeight);
                                                        args.SetContents(resized);
                                                    };
        }

        if (ImageUploadComplete != null)
        {
            ajaxFileUpload.UploadComplete += ImageUploadComplete;
        }
        popupdiv.Controls.Add(ajaxFileUpload);

        HtmlGenericControl btnCancel = new HtmlGenericControl("div");
        btnCancel.Attributes.Add("Id", this.ClientID + "_btnCancel");
        btnCancel.Attributes.Add("style", "float: right; position:relative; padding-left: 20px; top:10px; width: 55px; border-color:black;border-style: solid; border-width: 1px;cursor:pointer;");
        btnCancel.Attributes.Add("float", "right");
        btnCancel.Attributes.Add("unselectable", "on");
        btnCancel.InnerText = "Cancel";
        popupdiv.Controls.Add(btnCancel);

        this.Controls.Add(popupdiv);
    }
}

我使用此代码调整图像大小:

private byte[] ResizeImage(byte[] imageBytes, int maxWidth, int maxHeight)
{
    using (var memStream = new MemoryStream(imageBytes))
    {
        return ResizeImage(memStream, maxWidth, maxHeight);
    }
}

/// <summary>
/// Resizes images to the specified size.
/// </summary>
/// <param name="imageStream">The file stream.</param>
/// <param name="maxWidth">Maximum Width</param>
/// <param name="maxHeight">Maximum Height</param>
private byte[] ResizeImage(System.IO.Stream imageStream, int maxWidth, int maxHeight)
{
    byte[] result;
    try
    {
        using (System.Drawing.Bitmap originalBMP = new System.Drawing.Bitmap(imageStream))
        {
            // Calculate the new image dimensions
            int width = originalBMP.Width; //actual width
            int height = originalBMP.Height; //actual height
            int widthDiff = (width - maxWidth); //how far off maxWidth?
            int heightDiff = (height - maxHeight); //how far off maxHeight?

            //figure out which dimension is further outside the max size
            bool doWidthResize = (maxWidth > 0 && width > maxWidth && widthDiff > -1 && (widthDiff > heightDiff || maxHeight.Equals(0)));
            bool doHeightResize = (maxHeight > 0 && height > maxHeight && heightDiff > -1 && (heightDiff > widthDiff || maxWidth.Equals(0)));

            //only resize if the image is bigger than the max or where image is square, and the diffs are the same
            if (doWidthResize || doHeightResize || (width.Equals(height) && widthDiff.Equals(heightDiff)))
            {
                int iStart;
                Decimal divider;
                if (doWidthResize)
                {
                    iStart = width;
                    divider = Math.Abs((Decimal)iStart / (Decimal)maxWidth);
                    width = maxWidth;
                    height = (int)Math.Round((Decimal)(height / divider));
                }
                else
                {
                    iStart = height;
                    divider = Math.Abs((Decimal)iStart / (Decimal)maxHeight);
                    height = maxHeight;
                    width = (int)Math.Round((Decimal)(width / divider));
                }
            }

            using (System.Drawing.Bitmap newBMP = new System.Drawing.Bitmap(originalBMP, width, height))
            {
                using (System.Drawing.Graphics oGraphics = System.Drawing.Graphics.FromImage(newBMP))
                {
                    oGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                    oGraphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    oGraphics.DrawImage(originalBMP, 0, 0, width, height);
                    oGraphics.Save();
                }

                result = (new ImageConverter()).ConvertTo(newBMP, typeof(byte[])) as byte[];
            }
        }
    }
    catch (Exception)
    {
        result = null;
    }

    return result;
}

顺便说一句,您还必须更改Server/AjaxControlToolkit/AjaxFileUpload/AjaxFileUploadEventArgs文件以允许更改上传的文件内容:您需要添加SetContents如下方法:

internal void SetContents(byte[] value)
{
    _contents = value;
}
于 2012-10-20T20:28:12.020 回答