ASP.net 图像缩略图变成灰度(ish) - 奇怪!

发布于 2024-10-01 03:38:07 字数 5207 浏览 0 评论 0 原文

给定原始图像:

alt text

这会调整大小,如下所示:

alt text sstatic.net/1XOA8.png" alt="alt text">

服务器上存储的所有图像均正确,具有蓝色渐变背景。但当调整大小并提供服务时,它会显示黑色背景!并显着变暗。

在我的本地服务器上没有问题,它只在实时服务器上执行此操作!

我的缩略图代码是:

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

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

public class Thumbnail : IHttpHandler {

    private int _thumbnailSize = 150;

    public void ProcessRequest(HttpContext context) {

        // Name of photo file
        string photoName = context.Request.QueryString["p"];

        // Size index
        string sizeIndex = context.Request.QueryString["s"];
        string saveAction = context.Request.QueryString["a"];
        int width;
        int height;
        int maxWidth = 0;
        int maxHeight = 0;
        Bitmap photo;
        bool customResize = false;

        //Get original path of picture
        string photoPath = "";
        if (photoName.IndexOf('/') > 0)
        {
            photoPath = context.Server.MapPath(photoName);
        }
        else
        {

            photoPath = context.Server.MapPath("../uploads/originals/" + photoName);
        }

        // Create new bitmap
        try {
            photo = new Bitmap(photoPath);
        }
        catch (ArgumentException) {
            throw new HttpException(404, "Photo not found.");
        }
        context.Response.ContentType = "image/png";

        // Initialise width as native
        width = photo.Width;
        height = photo.Height;

        // Slideshow image (big)
        if (sizeIndex == "1")
        {
            // Set max widths and heights
            maxWidth = 500;
            maxHeight = 300;
            customResize = true;

        }
        // Big(ger) thumbnail
        else if (sizeIndex == "3")
        {
            // Set max widths and heights
            maxWidth = 150;
            maxHeight = 150;
            customResize = true;

        }
        // Big(ger) thumbnail
        else if (sizeIndex == "4")
        {
            // Set max widths and heights
            maxWidth = 30;
            maxHeight = 30;
            customResize = true;
        }
        // Standard thumbnail
        else
        {
            maxHeight = 75;

            // Normalise height
            if (photo.Height > maxHeight)
            {
                height = maxHeight;
                double newWidth = photo.Width / (photo.Height / height);
                width = int.Parse(newWidth.ToString());
            }
            else
            {
                height = photo.Height;
                width = photo.Width;
            }
        }

        // Resize
        if (customResize && (width > maxWidth || height > maxHeight))
        {

            double scale = Math.Min(1, Math.Min((double)maxWidth / (double)photo.Width, (double)maxHeight / (double)photo.Height));
            width = int.Parse((Math.Round((double)photo.Width * scale,0)).ToString());
            height = int.Parse((Math.Round((double)photo.Height * scale,0)).ToString());
        }

        // Generate and show image
        Bitmap target = new Bitmap(width, height);
        using (Graphics graphics = Graphics.FromImage(target)) {
            graphics.CompositingQuality = CompositingQuality.HighSpeed;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.DrawImage(photo, 0, 0, width, height);
            using (MemoryStream memoryStream = new MemoryStream()) {
                target.Save(memoryStream, ImageFormat.Png);
                //OutputCacheResponse(context, File.GetLastWriteTime(photoPath));
                //using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew)) {
                //    memoryStream.WriteTo(diskCacheStream);
                //}

                // If savinf
                if (saveAction == "s")
                {
                    FileStream outStream = File.OpenWrite(context.Server.MapPath("../uploads/gallery/" + photoName));
                    memoryStream.WriteTo(outStream);
                    outStream.Flush();
                    outStream.Close();
                }
                else{
                    memoryStream.WriteTo(context.Response.OutputStream);   
                }
            }
        }



    }

    private static void OutputCacheResponse(HttpContext context, DateTime lastModified) {
       /*   HttpCachePolicy cachePolicy = context.Response.Cache;
            cachePolicy.SetCacheability(HttpCacheability.Public);
            cachePolicy.VaryByParams["p"] = true;
            cachePolicy.SetOmitVaryStar(true);
            cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(7));
            cachePolicy.SetValidUntilExpires(true);
            cachePolicy.SetLastModified(lastModified);*/
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

Given an original image of:

alt text

This resizes to look as such:

alt text

ALL the images being stores on the server are correct with BLUE gradient background. But when it is resized and served it shows with black background! And darkened considerably.

On my local server there is no problem, it only does this on the live server!

My thumbnailing code is:

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

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

public class Thumbnail : IHttpHandler {

    private int _thumbnailSize = 150;

    public void ProcessRequest(HttpContext context) {

        // Name of photo file
        string photoName = context.Request.QueryString["p"];

        // Size index
        string sizeIndex = context.Request.QueryString["s"];
        string saveAction = context.Request.QueryString["a"];
        int width;
        int height;
        int maxWidth = 0;
        int maxHeight = 0;
        Bitmap photo;
        bool customResize = false;

        //Get original path of picture
        string photoPath = "";
        if (photoName.IndexOf('/') > 0)
        {
            photoPath = context.Server.MapPath(photoName);
        }
        else
        {

            photoPath = context.Server.MapPath("../uploads/originals/" + photoName);
        }

        // Create new bitmap
        try {
            photo = new Bitmap(photoPath);
        }
        catch (ArgumentException) {
            throw new HttpException(404, "Photo not found.");
        }
        context.Response.ContentType = "image/png";

        // Initialise width as native
        width = photo.Width;
        height = photo.Height;

        // Slideshow image (big)
        if (sizeIndex == "1")
        {
            // Set max widths and heights
            maxWidth = 500;
            maxHeight = 300;
            customResize = true;

        }
        // Big(ger) thumbnail
        else if (sizeIndex == "3")
        {
            // Set max widths and heights
            maxWidth = 150;
            maxHeight = 150;
            customResize = true;

        }
        // Big(ger) thumbnail
        else if (sizeIndex == "4")
        {
            // Set max widths and heights
            maxWidth = 30;
            maxHeight = 30;
            customResize = true;
        }
        // Standard thumbnail
        else
        {
            maxHeight = 75;

            // Normalise height
            if (photo.Height > maxHeight)
            {
                height = maxHeight;
                double newWidth = photo.Width / (photo.Height / height);
                width = int.Parse(newWidth.ToString());
            }
            else
            {
                height = photo.Height;
                width = photo.Width;
            }
        }

        // Resize
        if (customResize && (width > maxWidth || height > maxHeight))
        {

            double scale = Math.Min(1, Math.Min((double)maxWidth / (double)photo.Width, (double)maxHeight / (double)photo.Height));
            width = int.Parse((Math.Round((double)photo.Width * scale,0)).ToString());
            height = int.Parse((Math.Round((double)photo.Height * scale,0)).ToString());
        }

        // Generate and show image
        Bitmap target = new Bitmap(width, height);
        using (Graphics graphics = Graphics.FromImage(target)) {
            graphics.CompositingQuality = CompositingQuality.HighSpeed;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.DrawImage(photo, 0, 0, width, height);
            using (MemoryStream memoryStream = new MemoryStream()) {
                target.Save(memoryStream, ImageFormat.Png);
                //OutputCacheResponse(context, File.GetLastWriteTime(photoPath));
                //using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew)) {
                //    memoryStream.WriteTo(diskCacheStream);
                //}

                // If savinf
                if (saveAction == "s")
                {
                    FileStream outStream = File.OpenWrite(context.Server.MapPath("../uploads/gallery/" + photoName));
                    memoryStream.WriteTo(outStream);
                    outStream.Flush();
                    outStream.Close();
                }
                else{
                    memoryStream.WriteTo(context.Response.OutputStream);   
                }
            }
        }



    }

    private static void OutputCacheResponse(HttpContext context, DateTime lastModified) {
       /*   HttpCachePolicy cachePolicy = context.Response.Cache;
            cachePolicy.SetCacheability(HttpCacheability.Public);
            cachePolicy.VaryByParams["p"] = true;
            cachePolicy.SetOmitVaryStar(true);
            cachePolicy.SetExpires(DateTime.Now + TimeSpan.FromDays(7));
            cachePolicy.SetValidUntilExpires(true);
            cachePolicy.SetLastModified(lastModified);*/
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

桃扇骨 2024-10-08 03:38:07

考虑到这似乎是一个显示问题,那么我从经验中发现的一些事情是,PNG 存储了您通常可能不希望它们用于多种用途的内容。该缩略图包含与颜色空间和其他此类内容相关的数据块。众所周知,这些东西会搞砸一些事情。我认为它们适合照片,但在进行 Web 工作并尝试将 PNG 中的颜色与页面中的 HTML 颜色相匹配时,它们可能会导致一场噩梦......

请看这里: http://the.earth.li/~chris/temp/tomgullenquestion_1XOA8.png

这是缩略图的副本修剪掉非关键块,以便您可以测试这是否会导致问题。

Given that it seems to be a display problem then a few things I've found from experience is that PNGs store stuff that you usually probably don't want them to for a lot of purposes. This thumbnail contains chunks of data relating to colour spaces and other such things. These have been known to screw stuff around a fair bit. I assume they are good for photos but they can cause a nightmare when doing web work and trying to match a colour in the PNG with an HTML colour in the page...

Look here: http://the.earth.li/~chris/temp/tomgullenquestion_1XOA8.png

This is a copy of the thumbnail image with the non-critical chunks trimmed out so you can test if that is contributing to the problem or not.

枫林﹌晚霞¤ 2024-10-08 03:38:07

我首先看到的是你没有处理 BitMap。

The first this I see is that you did not dispose the BitMap.

怀里藏娇 2024-10-08 03:38:07

我强烈建议您通过清除缓存进行测试(例如,Chrome 中的 CTRL-F5)。可能是您的图像(曾经)已损坏,并且缓存中正是该损坏的版本。

我也认为所提供的大/小版本没有问题。

I would strongly suggest you test by clearing your cache (CTRL-F5 in Chrome, for example). It could be that your image was (at one time) corrupted, and it is that corrupted version that is in the cache.

I, too, see no problems with the large/small version as presented.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文