如何从控制器方法返回一个形象? [英] How to return an image from a controller method?

查看:92
本文介绍了如何从控制器方法返回一个形象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在MP3文件中的MP3 albumart,使用标签库。我使用的code,它给人的 System.Drawing.Bitmap 。如何在网页上显示。我使用MVC。

I want to take the mp3 albumart in the mp3 file, using TagLib. I am using that code, it gives the System.Drawing.Bitmap. How to display in the Webpage. I am Using MVC.

var file12 = TagLib.File.Create(file);

if (file12.Tag.Pictures.Length >= 1)
{
    var bin = (byte[])(file12.Tag.Pictures[0].Data.Data);
    if (bin.Length > 0)
    {
        Images = System.Drawing.Image.FromStream(new MemoryStream(bin)).GetThumbnailImage(200, 200, null, IntPtr.Zero);
        album = file12.Tag.Album;
    }
}

请帮我

推荐答案

只要把该code中的控制器的方法,图像将被异步加载(在本实施例的控制器方法接受文件名作为参数,它可能无法你的情况):

Just put that code in a controller method, image will be loaded asynchronously (in this example controller method accepts file name as parameter, it may not be your case):

public ActionResult GetImage(string file)
{
    var file12 = TagLib.File.Create(file);
    if (file12.Tag.Pictures.Length >= 1)
    {
        string fileName = Path.ChangeExtension(
            Path.GetFileName(file), ".jpg");

        return base.File(
            (byte[])(file12.Tag.Pictures[0].Data.Data),
            "image/jpeg", fileName);
    }

    // You have to handle this case
    return null;
}

<一个href=\"http://msdn.microsoft.com/en-us/library/dd470835%28v=vs.118%29.aspx?cs-save-lang=1&cs-lang=csharp#$c$c-snippet-1\"相对=nofollow> Controller.File()方法会做所有的肮脏的工作适合你。为了清楚在这个例子中我省略了重新调节,只需复制和放大器;如果需要粘贴code那里。请注意,您必须返回的东西时,没有图像不可用(?一个默认的缩略图),你甚至可以返回一个HTTP错误有:

Controller.File() method will do all the dirty job for you. For clarity in this example I omitted rescaling, just copy & paste your code there if needed. Please note you have to return something when no image is not available (a default thumbnail?), you may even return a HTTP error with:

return HttpNotFound();

您的HTML将例如这样的:

Your HTML will be for example like this:

<img
     src='@Url.Action("GetImage", new { file = "filenamehere.mp3" })'
     alt='thumbnail' />

请注意,我在这里假设你的形象是JPG格式,如果它不是你可能需要将其转换为已知的格式返回正确的MIME类型(检测从字节流MIME类型也是可能的,检查<一href=\"http://stackoverflow.com/questions/10040330/how-to-extract-file-extension-from-byte-array\">this帖子这里SO)。

Please note that here I assumed your image is in JPG format, if it's not you may need to convert it to a known format to return proper MIME type (to detect MIME type from byte stream is possible too, check this post here on SO).

这篇关于如何从控制器方法返回一个形象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆