English 中文(简体)
将任何图像尺寸图像转化为400Wx264 H 采用c# for asp.net web application
原标题:resize any image size image into 400Wx264H using c# for asp.net web application

我正在设计一个网站,需要将大幅图像重新塑造为400Wx264H的层面,而无需疏漏。

我致力于不同的法典文本,但都回过来。

现在,在保持相关比例的同时,将大图像转成400瓦,然后允许用户选择使用jCrop的部分图像是可选择的领域350瓦克斯230H。

有时,如果图像重的高度或宽度小于400瓦或264赫克,则会给图像增加黑部分。

如果有人能向我指出我必须做的一些类似事情,我将不胜感激。

CODE for Upload and resizing culture is BELOW

public void ResizeImageFreeSize(string OriginalFile, string NewFile, int NewWidth, int MaxHeight, bool OnlyResizeIfWider, string fileExtension)
    {
        System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFile);
        // Prevent using images internal thumbnail
        //FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        //FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone);
        //if (OnlyResizeIfWider)
        //{
        //    if (FullsizeImage.Width <= NewWidth)
        //    {
        //        NewWidth = FullsizeImage.Width;
        //    }
        //}
        //int NewHeight = FullsizeImage.Height * NewWidth / FullsizeImage.Width;
        //if (NewHeight > MaxHeight)
        //{
        //    // Resize with height instead
        //    NewWidth = FullsizeImage.Width * MaxHeight / FullsizeImage.Height;
        //    NewHeight = MaxHeight;
        //}
        System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(NewWidth, MaxHeight, null, IntPtr.Zero);
        // Clear handle to original file so that we can overwrite it if necessary
        FullsizeImage.Dispose();
        // Save resized picture

        if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".jpeg")
        {
            //NewImage.Save(NewFile, System.Drawing.Imaging.ImageFormat.Jpeg);

            Encoder quality = Encoder.Quality;
            var ratio = new EncoderParameter(quality, 100L);
            var codecParams = new EncoderParameters(1);
            codecParams.Param[0] = ratio;
            NewImage.Save(NewFile, GetEncoder(ImageFormat.Jpeg), codecParams);
        }

        if (fileExtension.ToLower() == ".png")
        {
            NewImage.Save(NewFile, System.Drawing.Imaging.ImageFormat.Png);
        }

        if (fileExtension.ToLower() == ".gif")
        {
            NewImage.Save(NewFile, System.Drawing.Imaging.ImageFormat.Gif);
        }
    }

ABOVE code upload the large image and re size it to fixed size of 400x264 pixels. but this approach stretches the image as i have comments the code which maintains the aspect ration.

在重层图像上载后,即允许用户从这种图像中选取该地区,可选择可选取350x230皮克。

这部作品没有任何问题,但形象紧张。

protected void btnCrop_Command(object sender, CommandEventArgs e)
{
    cropImage();
    // pnlImageDetails.Visible = true;
}

protected void cropImage()
{
    var x = int.Parse(_xField.Value);
    var y = int.Parse(_yField.Value);
    var width = int.Parse(_widthField.Value);
    var height = int.Parse(_heightField.Value);
    string _CropImagePath = Session["_CropImagePath"].ToString();
    using (var photo = System.Drawing.Image.FromFile(_CropImagePath))
    using (var result =
          new Bitmap(width, height, photo.PixelFormat))
    {
        result.SetResolution(photo.HorizontalResolution, photo.VerticalResolution);
        using (var g = Graphics.FromImage(result))
        {
            // g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.DrawImage(photo, new Rectangle(0, 0, width, height),
                               new Rectangle(x, y, width, height),
                                             GraphicsUnit.Pixel);
            photo.Dispose();
            result.Save(_CropImagePath);
            string filePath = _CropImagePath.ToString();
            System.IO.FileInfo f = new System.IO.FileInfo(filePath);
            string fileExtension = f.Extension;
            string fileName = f.Name;
            string[] fNameArray = fileName.Split( . );
            string fileNewName = fNameArray[0] + "TN" + f.Extension;
            Session["ArticleThumbnailImage"] = fileNewName;
            string fileNewPath = Server.MapPath("../ImagesArticles/") + fileNewName;
            ResizeImageFreeSize(filePath, fileNewPath, 170, 112, true, fileExtension);
        }

    }
}

页: 1

 <div id="ImageEditorFrame" style="width:800px; height:350px; float:left; ">

    <div style="width:404px; height:268px; margin-left:160px; margin-top:10px; padding-top:1px;  background-image:url( images/Scale.png ); background-repeat:no-repeat;">
        <div style="width:400px; height:264px; margin-left:3px; margin-top:2px; padding-top:1px; background-color:#f5f5f5;">
            <asp:Image runat="server" ID="_imageEditor" ImageUrl="" Visible="true" />   

        </div>
        <div style="margin-top:10px;"> 
         <asp:Button ID="btnCrop" runat="server" style="float:left;"  Text=" Crop Image " Visible="False" oncommand="btnCrop_Command"  />
        <input id="w" type="text" name="w" size="4" disabled="disabled">
        <input id="h" type="text" name="h" size="4" disabled="disabled">(350x230)<br /><br />
        <asp:Label ID="lblUplodedImgInfo" runat="server" Text=""></asp:Label>
        </div>
    </div>


    <input type="hidden" runat="server" id="_xField" />
    <input type="hidden" runat="server" id="_yField" />
    <input type="hidden" runat="server" id="_widthField" />
    <input type="hidden" runat="server" id="_heightField" />



</div>

var editorID =  <%= _imageEditor.ClientID %> ;
jQuery(function () {
    jQuery( #  + editorID).Jcrop({
        onChange: showCoords,
        onSelect: showCoords,
        setSelect: [0, 0, 350, 230],
        allowResize: false
    });
});

function showCoords(c) {

    var xField = document.getElementById( <%= _xField.ClientID %> );
    var yField = document.getElementById( <%= _yField.ClientID %> );
    var widthField = document.getElementById( <%= _widthField.ClientID %> );
    var heightField = document.getElementById( <%= _heightField.ClientID %> );

    xField.value = c.x;
    yField.value = c.y;
    widthField.value = 350;
    heightField.value = 230;
    $( #w ).val(c.w);
    $( #h ).val(c.h);
}

Screen Shot for idea Screen Shot for idea

如果能让用户拥有选择图像和图像领域的功能,并由此形成重新形象,我将热心这样做。 如今,法典并没有产生完美的结果。

如果有人能够帮助我,我就是一个完整的工作榜样。

关于

最佳回答

如果我正确理解,你的最终目标是最终达到350x230px thumbnail的形象,但你希望用户能够根据400x264px的预览选择作物。 不幸的是,你在预审中重新强制实行一个方面的比例,这就是为什么你重新陷入扭曲。 如果你把400x264px的层面视为最低点,那么你就可以根据那些不会被歪曲的污染物而产生th。

public static void ResizeImageFreeSize(string OriginalFile, string NewFile, int MinWidth, int MinHeight, string FileExtension)
{
    var NewHeight = MinHeight;
    var NewWidth = MinWidth;        
    var OriginalImage = Image.FromFile(OriginalFile);

    if (OriginalImage.Width < MinWidth || OriginalImage.Height < MinHeight)
        throw new Exception(String.Format("Invalid Image Dimensions, please upload an image with minmum dimensions of {0}x{1}px", MinWidth.ToString(), MinHeight.ToString()));

    // If the image dimensions are the same then make the new dimensions the largest of the two mins.
    if (OriginalImage.Height == OriginalImage.Width)
        NewWidth = NewHeight = (MinWidth > MinHeight) ? MinWidth : MinHeight;
    else
    {
        if (MinWidth > MinHeight)
            NewHeight = (int)(OriginalImage.Height * ((float)MinWidth / (float)OriginalImage.Width));
        else
            NewWidth  = (int)(OriginalImage.Width * ((float)MinHeight / (float)OriginalImage.Height));
    }

    // Just resample the Original Image into a new Bitmap
    var ResizedBitmap = new System.Drawing.Bitmap(OriginalImage, NewWidth, NewHeight);

    // Saves the new bitmap in the same format as it s source image
    FileExtension = FileExtension.ToLower().Replace(".","");

    ImageFormat Format = null;
    switch (FileExtension)
    {
        case "jpg":
            Format = ImageFormat.Jpeg;
            break;
        case "gif":
            Format = ImageFormat.Gif;
            break;
        case "png":
            Format = ImageFormat.Png;
            break;
        default:
            Format = ImageFormat.Png;
            break;
    }

    ResizedBitmap.Save(NewFile, Format);


    // Clear handle to original file so that we can overwrite it if necessary
    OriginalImage.Dispose();
    ResizedBitmap.Dispose();
}
问题回答

You can either maintain aspect ratio or hard limit on dimensions of image i.e. 400x264 If you want to maintain aspect ratio your resized image should be reduced by factor of min(finalWidth/orignalWidth, finalHeight/orignalHeight)

See See See

<><>><>>>>> 我将用他的逻辑作一些改动,以表明他的回答是正确的。

我编辑了这部法典,增加了两点,一是由于锁定了这样一来的记忆犹新,因此出现了错误。 守则的另一个问题是,它正在为JPG生成的低效图像,即增加了编码范围。 逻辑的中止相同,即没有改变

public static void ResizeImageFreeSize(string OriginalFile, string NewFile, int MinWidth, int MinHeight, string FileExtension)
{
    var NewHeight = MinHeight;
    var NewWidth = MinWidth;
    // var OriginalImage = System.Drawing.Image.FromFile(OriginalFile); // THis statlement alon with generate error as file is locked so -->//GDI+ keeps a lock on files from which an image was contructed.  To avoid the lock, construct the image from a MemorySteam:

    MemoryStream ms = new MemoryStream(File.ReadAllBytes(OriginalFile));
    var OriginalImage = System.Drawing.Image.FromStream(ms);

    if (OriginalImage.Width < MinWidth || OriginalImage.Height < MinHeight)
        throw new Exception(String.Format("Invalid Image Dimensions, please upload an image with minmum dimensions of {0}x{1}px", MinWidth.ToString(), MinHeight.ToString()));

    // If the image dimensions are the same then make the new dimensions the largest of the two mins.
    if (OriginalImage.Height == OriginalImage.Width)
        NewWidth = NewHeight = (MinWidth > MinHeight) ? MinWidth : MinHeight;
    else
    {
        if (MinWidth > MinHeight)
            NewHeight = (int)(OriginalImage.Height * ((float)MinWidth / (float)OriginalImage.Width));
        else
            NewWidth = (int)(OriginalImage.Width * ((float)MinHeight / (float)OriginalImage.Height));
    }

    // Just resample the Original Image into a new Bitmap
    var ResizedBitmap = new System.Drawing.Bitmap(OriginalImage, NewWidth, NewHeight);

    // Saves the new bitmap in the same format as it s source image
    FileExtension = FileExtension.ToLower().Replace(".", "");

    ImageFormat Format = null;
    switch (FileExtension)
    {
        case "jpg":
            Format = ImageFormat.Jpeg;

            Encoder quality = Encoder.Quality;
            var ratio = new EncoderParameter(quality, 100L);
            var codecParams = new EncoderParameters(1);
            codecParams.Param[0] = ratio;
            // NewImage.Save(NewFile, GetEncoder(ImageFormat.Jpeg), codecParams);
            ResizedBitmap.Save(NewFile, GetEncoder(ImageFormat.Jpeg), codecParams);
            break;
        case "gif":
            Format = ImageFormat.Gif;
            ResizedBitmap.Save(NewFile, Format);
            break;
        case "png":
            Format = ImageFormat.Png;
            ResizedBitmap.Save(NewFile, Format);
            break;
        default:
            Format = ImageFormat.Png;
            ResizedBitmap.Save(NewFile, Format);
            break;
    }

    //  ResizedBitmap.Save(NewFile, Format);


    // Clear handle to original file so that we can overwrite it if necessary
    OriginalImage.Dispose();
    ResizedBitmap.Dispose();
}

private static ImageCodecInfo GetEncoder(ImageFormat format)
{
    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
    foreach (ImageCodecInfo codec in codecs)
        if (codec.FormatID == format.Guid)
            return codec;
    return null;
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签