How can I generate a thumbnail from an image in server folder?

给你一囗甜甜゛ 提交于 2019-12-12 01:33:39

问题


I've been trying to figure this out but I'm not getting anywhere. What I'm trying to do is this: I have a aspx page where you can upload images (they are stored in a folder on the server), on one page you can see all the uploaded images and it generates links (a tags) with a reference to these images, but until now it loaded the full images as a "thumbnail" and they are far too large in size (1920x1200px), So I replaced the image src with a generic handler, which should get the image from the folder and then return it, resized to say like 209x133px.

But I have no idea where to start and I would appreciate any held, maybe someone out there once did somethin similar.

Anyway, thanks in advance

This is how I ceate the links and images with a repeater:

protected void repImages_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if (e.Item.ItemType == ListItemType.AlternatingItem ||
        e.Item.ItemType == ListItemType.Item)
    {
        string sFile = e.Item.DataItem as string;

        //Create the thumblink
        HyperLink hlWhat = e.Item.FindControl("hlWhat") as HyperLink;
        hlWhat.NavigateUrl = ResolveUrl("~/_img/_upload/" + sFile);
        hlWhat.ToolTip = System.IO.Path.GetFileNameWithoutExtension(sFile);
        hlWhat.Attributes["rel"] = "imagebox-bw";
        hlWhat.Attributes["target"] = "_blank";

        Image oImg = e.Item.FindControl("imgTheImage") as Image;
        oImg.ImageUrl = ResolveUrl("Thumbnail.ashx?img=" + sFile);
        oImg.Width = 203;
        oImg.CssClass = "galleryImgs";

    }

}

and for now, my handler look like this:

<%@ WebHandler Language="C#" Class="Thumbnail" %>

using System;
using System.Web;

public class Thumbnail : IHttpHandler {

    public void ProcessRequest (HttpContext context) {
        if (!string.IsNullOrEmpty(context.Request.QueryString["img"]))
        {
            string fileName = context.Request.QueryString["img"];

        }

        else
        {

        }

    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

回答1:


Adding System.Drawing and System.Drawing.Drawing2D namespaces you Can resize your image CodeBehind:

public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
  {
      var ratio = (double)maxHeight / image.Height;
      var newWidth = (int)(image.Width * ratio);
      var newHeight = (int)(image.Height * ratio);
      var newImage = new Bitmap(newWidth, newHeight);
      using (var g = Graphics.FromImage(newImage))
      {
          g.DrawImage(image, 0, 0, newWidth, newHeight);
      }
      return newImage;
  }

Detailed Article: How to Resize Image While Uploading in Asp.net C#




回答2:


Here is some code that may need some tweaks, but can help you move on.

// 1x1 transparent GIF
private readonly byte[] GifData = {
    0x47, 0x49, 0x46, 0x38, 0x39, 0x61,
    0x01, 0x00, 0x01, 0x00, 0x80, 0xff,
    0x00, 0xff, 0xff, 0xff, 0x00, 0x00,
    0x00, 0x2c, 0x00, 0x00, 0x00, 0x00,
    0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
    0x02, 0x44, 0x01, 0x00, 0x3b
};

public void ProcessRequest(HttpContext context)
{
    // render direct
    context.Response.BufferOutput = false;

    bool fFail = true;

    try
    {
      if (!string.IsNullOrEmpty(context.Request.QueryString["img"]))
      {
        string fileName = context.Request.QueryString["img"];         

        using( var inputImage = new Bitmap(fileName))
        {   
            // create the thubnail
            FinalImage = CreateThubNain();          

            // send it to browser
            FinalImage.Save(context.Response.OutputStream, ImageFormat.Jpeg);           
            // flag tha all ends up well
            fFail = false;
        }          
      }
    }
    catch(Exception x)
    {
        // log the error
        Debug.Fail("Check why is fail - error:" + x.ToString());
    }

    if(fFail)
    {
        // send something anyway
        context.Response.ContentType = "image/gif";
        context.Response.OutputStream.Write(GifData, 0, GifData.Length);
    }
    else
    {
        // this is a header that you can get when you read the image
        context.Response.ContentType = "image/jpeg";

        // the size of the image, saves from load the image, and send it here
        // context.Response.AddHeader("Content-Length", imageData.Length.ToString());

        // cache the image - 24h example
        context.Response.Cache.SetExpires(DateTime.Now.AddHours(24));
        context.Response.Cache.SetMaxAge(new TimeSpan(24, 0, 0));   
    }
}

and one question on how to make the Thubnail: make thumbnail from database image while keeping aspect ratio

Some comments. If you use a handler to make the thumbnails you spend a lot of proceesing time to make the same and same again. I suggest to keep track of the thumbnails and save them on disk, and then use direct the file from disk.




回答3:


We use a method like this:

private Image ScaleFreeHeight(string imagePath, int newWidth)
{
    var byteArray = new StreamReader(imagePath).BaseStream;        
    var image = Image.FromStream(byteArray);
    var newHeight2 = Convert.ToInt32(newWidth * (1.0000000 * image.Height / image.Width));
    var thumbnail = new Bitmap(newWidth, newHeight2);
    var graphic = Graphics.FromImage(thumbnail);
    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
    graphic.SmoothingMode = SmoothingMode.HighQuality;
    graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
    graphic.CompositingQuality = CompositingQuality.HighQuality

    graphic.DrawImage(image, 0, 0, newWidth, newHeight2);

    return thumbnail;
}


来源:https://stackoverflow.com/questions/13988269/how-can-i-generate-a-thumbnail-from-an-image-in-server-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!