C# 用C语言创建缩略图#

C# 用C语言创建缩略图#,c#,asp.net-mvc-3,razor,gdi+,jpeg,C#,Asp.net Mvc 3,Razor,Gdi+,Jpeg,但我在那个文件夹里的所有照片都有“.jpg”的扩展名,所以对我来说似乎很奇怪。 如果我不能从“.jpg”创建缩略图,我还能做什么 我真的想知道是否有人在“.jpg”文件上尝试过这个,但遇到了问题?如果没有问题,我可能做错了什么 注意:我使用razor语法在视图中执行此操作。我对c#语言略知一二,每天都在提高我的c#语言知识 编辑: 如何调用函数: // // Summary: // Creates an System.Drawing.Image from the

但我在那个文件夹里的所有照片都有“.jpg”的扩展名,所以对我来说似乎很奇怪。 如果我不能从“.jpg”创建缩略图,我还能做什么

我真的想知道是否有人在“.jpg”文件上尝试过这个,但遇到了问题?如果没有问题,我可能做错了什么

注意:我使用razor语法在视图中执行此操作。我对c#语言略知一二,每天都在提高我的c#语言知识

编辑:

如何调用函数:

    //
    // Summary:
    //     Creates an System.Drawing.Image from the specified file.
    //
    // Parameters:
    //   filename:
    //     A string that contains the name of the file from which to create the System.Drawing.Image.
    //
    // Returns:
    //     The System.Drawing.Image this method creates.
    //
    // Exceptions:
    //   System.OutOfMemoryException:
    //     The file does not have a valid image format.-or- GDI+ does not support the
    //     pixel format of the file.
    //
    //   System.IO.FileNotFoundException:
    //     The specified file does not exist.
    //
    //   System.ArgumentException:
    //     filename is a System.Uri.
    [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
    public static Image FromFile(string filename);

文件扩展名并不重要,重要的是图像的实际字节数。最有可能的是其中一个JPG腐败。您应该在每个文件的基础上捕获OutOfMemory异常,并进行适当的处理

由于您正在尝试生成缩略图,因此如果无法生成缩略图,我建议您使用默认图像。例如,当图像损坏或丢失时,大多数web浏览器都会使用带有红色X的小方框

另见:

对于那些对抛出OutOfMemoryException的原因感到好奇的人,请参见此问题的答案:

我工作的网站使用WPF API而不是GDI+生成缩略图。您需要向项目添加两个引用以启用此功能:WindowsBase、PresentationFramework和PresentationCore。下面是如何使用代码的基本示例:

GetThumbnailView("../pics/thumb_" + (("0000000" + stocks.stockcode).Substring(("0000000" + stocks.stockcode).Length - 7, 7)) + ".jpg", 200, 200);
这将使缩略图适合200x100矩形,同时保留纵横比

(真实的网站并不像上面所说的那样。我们实际做的是尝试在文件上传帖子处理程序中生成最小的缩略图。我们使用内存流保存生成的缩略图。如果缩略图生成正确,我们将保存上传和小缩略图,否则我们将向cl返回错误响应。)客户端。动态生成并缓存其他缩略图大小。)

下面是代码-请注意,在将其转换为可重用的内容时,我可能弄错了一点,但核心部分应该都在那里。请注意,它将所有缩略图保存为JPEG格式,但允许多种输入格式,包括JPEG和PNG。这对您可能合适,也可能不合适

try
{
    using (var input = File.Open(inputFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
    using (var thumb = File.Open(thumbFilename, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        Thumbnail(input, thumb, 200, 100);
    }
}
catch (MyException)
{
    File.Delete(thumbFilename);
}
私有静态无效缩略图(流源、流目标、int-maxWidth、int-maxHeight)
{
整数宽度=0,高度=0;
BitmapFrame=null;
尝试
{
frame=BitmapDecoder.Create(源,BitmapCreateOptions.None,BitmapCacheOption.None)。Frames[0];
宽度=帧。像素宽度;
高度=帧。像素高度;
}
抓住
{
抛出新的MyException(“图像文件不是任何受支持的图像格式。”);
}
if(宽度>绝对最大上载宽度| |高度>绝对最大上载高度)
抛出新的MyException(“此图像太大”);
尝试
{
int targetWidth,targetHeight;
使用纵横比调整大小(宽度、高度、最大宽度、最大高度、超出目标宽度、超出目标宽度);
位图帧目标帧;
if(frame.PixelWidth==targetWidth&&frame.PixelHeight==targetHeight)
targetFrame=帧;
其他的
{
var group=新绘图组();
SetBitmapScalingMode(组,BitmapScalingMode.HighQuality);
添加(新的图像绘制(帧,新的矩形(0,0,targetWidth,targetSight));
var targetVisual=new DrawingVisual();
var targetContext=targetVisual.RenderOpen();
targetContext.DrawDrawing(组);
var target=新的RenderTargetBitmap(targetWidth、targetLight、96、96、PixelFormats.Default);
targetContext.Close();
target.Render(targetVisual);
targetFrame=BitmapFrame.Create(目标);
}
var enc=新的JpegBitmapEncoder();
附件框架添加(目标框架);
附件质量等级=80;
enc.Save(目的地);
}
抓住
{
抛出新的MyException(“图像文件似乎已损坏”);
}
}
///通用帮助器,用于计算符合指定最大值的宽度/高度,同时保留纵横比。
使用Aspect(int-origWidth、int-origHeight、int-maxWidth、int-maxHeight、out-int-sizedWidth、out-int-sizedHeight)调整公共静态空间大小
{
if(origWidthmaxHeight)
{
sizedHeight=最大高度;
sizedWidth=(int)((双)origWidth/origHeight*sizedHeight+0.5);
}
}

对于要抛出的
OutOfMemoryException
来说,这似乎是一个非常奇怪的描述。我只是对编写该异常的人失去了一点尊重。他们应该验证输入并抛出一个不同的异常。@David Yea告诉我吧!我花了10分钟才明白发生了什么。你确定要传递的文件名是正确的吗不包括jpeg扩展名或其他扩展名?我指的是Server.MapPath(thumbnailImagePath)代码。它的末尾包含“.jpg”..这就是我调用函数的方式:
GetThumbnailView(../pics/thumb++)((“0000000”+stocks.stockkode).子字符串((“0000000”+stocks.stockkode).长度-7,7))+“.jpg”,200)
我们在web应用程序中使用WPF来缩略图像,而不是GDI+,并且API非常好。它们当然可以让您区分格式错误和OOM,同时支持许多流行的编解码器,并在解码之前让您知道宽度/高度。感兴趣吗?谢谢,但我不能只保留一张未找到图像的照片那里..如果存在图片,我必须生成一个缩略图,这样我就不能使用现有图片的默认图像,以及jpg文件如何损坏?是否可能是由于将jpg文件移动到另一个文件夹造成的?(我不认为这可能是
try
{
    using (var input = File.Open(inputFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
    using (var thumb = File.Open(thumbFilename, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        Thumbnail(input, thumb, 200, 100);
    }
}
catch (MyException)
{
    File.Delete(thumbFilename);
}
private static void Thumbnail(Stream source, Stream destination, int maxWidth, int maxHeight)
{
    int width = 0, height = 0;
    BitmapFrame frame = null;
    try
    {
        frame = BitmapDecoder.Create(source, BitmapCreateOptions.None, BitmapCacheOption.None).Frames[0];
        width = frame.PixelWidth;
        height = frame.PixelHeight;
    }
    catch
    {
        throw new MyException("The image file is not in any of the supported image formats.");
    }

    if (width > AbsoluteLargestUploadWidth || height > AbsoluteLargestUploadHeight)
        throw new MyException("This image is too large");

    try
    {
        int targetWidth, targetHeight;
        ResizeWithAspect(width, height, maxWidth, maxHeight, out targetWidth, out targetHeight);

        BitmapFrame targetFrame;
        if (frame.PixelWidth == targetWidth && frame.PixelHeight == targetHeight)
            targetFrame = frame;
        else
        {
            var group = new DrawingGroup();
            RenderOptions.SetBitmapScalingMode(group, BitmapScalingMode.HighQuality);
            group.Children.Add(new ImageDrawing(frame, new Rect(0, 0, targetWidth, targetHeight)));
            var targetVisual = new DrawingVisual();
            var targetContext = targetVisual.RenderOpen();
            targetContext.DrawDrawing(group);
            var target = new RenderTargetBitmap(targetWidth, targetHeight, 96, 96, PixelFormats.Default);
            targetContext.Close();
            target.Render(targetVisual);
            targetFrame = BitmapFrame.Create(target);
        }

        var enc = new JpegBitmapEncoder();
        enc.Frames.Add(targetFrame);
        enc.QualityLevel = 80;
        enc.Save(destination);
    }
    catch
    {
        throw new MyException("The image file appears to be corrupt.");
    }
}

/// <summary>Generic helper to compute width/height that fit into specified maxima while preserving aspect ratio.</summary>
public static void ResizeWithAspect(int origWidth, int origHeight, int maxWidth, int maxHeight, out int sizedWidth, out int sizedHeight)
{
    if (origWidth < maxWidth && origHeight < maxHeight)
    {
        sizedWidth = origWidth;
        sizedHeight = origHeight;
        return;
    }

    sizedWidth = maxWidth;
    sizedHeight = (int) ((double) origHeight / origWidth * sizedWidth + 0.5);
    if (sizedHeight > maxHeight)
    {
        sizedHeight = maxHeight;
        sizedWidth = (int) ((double) origWidth / origHeight * sizedHeight + 0.5);
    }
}