Asp.net MVC学习日记一(显示图片)

1、在Models文件中建ImageResult类,并继承自ActionResult

public class ImageResult:ActionResult
{
private string _path;
public ImageResult(string path)
{
_path = path;
}

public override void ExecuteResult(ControllerContext context)
{
byte[] bytes;
//no context? stop processing
if (context == null)
throw new ArgumentNullException("context");
//check for file
if (File.Exists(_path)) { bytes = File.ReadAllBytes(_path); }
else
{
throw new FileNotFoundException(_path);
}

string contentType = GetContentTypeFromFile();

HttpResponseBase response = context.HttpContext.Response;
response.ContentType = contentType;

MemoryStream imageStream = new MemoryStream(bytes);
byte[] buffer = new byte[4096];
while (true)
{
int read = imageStream.Read(buffer, 0, buffer.Length);
if (read == 0)
break;
response.OutputStream.Write(buffer, 0, read);
}
response.End();
}


private string GetContentTypeFromFile()
{
//get extension from path to determine contentType
string[] parts = _path.Split('.');
string extension = Path.GetExtension(_path).Substring(1);
string contentType;
switch (extension.ToLower())
{
case "jpeg":
case "jpg":
contentType = "image/jpeg";
break;
case "gif":
contentType = "image/gif";
break;

default:
throw new NotImplementedException(extension + "not handled");
}
return contentType;
}
}

2、在HomeController.cs文件中添加Action,名称GetImage,并返回ImageResult

public ImageResult GetImage()
{
return new ImageResult(@"C:\Users\Public\Pictures\Sample Pictures\tuyin.jpg");
}

最后直接访问http://localhost:13811/home/GetImage就可以显示图片了。

更进一步指定图片大小显示

1、Models文件夹下新建ImageResizeResult类

public class ImageResizeResult : ActionResult
{
private string _path;
private int _width;
private int _maximumHeight;
private bool _noZooming;

public ImageResizeResult(string fileName, int width,int maximumHeight, bool noZooming = false)
{
//put this path reference in a config file somewhere!
_path = @"C:\Users\Public\Pictures\Sample Pictures\" + fileName;
_width = width;
_maximumHeight = maximumHeight;
_noZooming = noZooming;
}

private ImageFormat GetImageFormatFromFile()
{
//get extension from path to determine contentType
string[] parts = _path.Split('.');
string extension = parts[parts.Length - 1];
ImageFormat imageFormat;

switch (extension.ToLower())
{
case "jpeg":
case "jpg":
imageFormat = ImageFormat.Jpeg;
break;
case "gif":
imageFormat = ImageFormat.Gif;
break;

default:
throw new NotImplementedException(extension + "not handled");
}
return imageFormat;
}

public Image ResizeImage(string imagePathToResize)
{
Image fullsizeImage;
//check for file
if (File.Exists(_path))
{
fullsizeImage = Image.FromFile(_path);
}
else
{
throw new FileNotFoundException(_path);
}
//load the image from the file system
fullsizeImage = Image.FromFile(_path);

// hack to prevent the internal thumbnail from being used!
fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);
fullsizeImage.RotateFlip(RotateFlipType.Rotate180FlipNone);

// can we zoom this image?
if (_noZooming)
{
if (fullsizeImage.Width <= _width)
{
_width = fullsizeImage.Width;
}
}
// determine new height
int newHeight = fullsizeImage.Height * _width / fullsizeImage.Width;
if (newHeight > _maximumHeight)
{
// Resize with height instead
_width = fullsizeImage.Width * _maximumHeight /
fullsizeImage.Height;
newHeight = _maximumHeight;
}

Image newImage = fullsizeImage.GetThumbnailImage(_width,newHeight, null, IntPtr.Zero);
//dispose of the in memory original
fullsizeImage.Dispose();
return newImage;
}

public override void ExecuteResult(ControllerContext context)
{
byte[] buffer = new byte[4096];

HttpResponseBase response = context.HttpContext.Response;
//no context? stop processing
if (context == null)
throw new ArgumentNullException("context");
//set files content type
response.ContentType = "image/" +
GetImageFormatFromFile().ToString();
//get the resized image
Image resizedImage = ResizeImage(_path);
MemoryStream ms = new MemoryStream();
resizedImage.Save(ms, GetImageFormatFromFile());
MemoryStream imageStream = new MemoryStream(ms.ToArray());
while (true)
{
int read = imageStream.Read(buffer, 0, buffer.Length);
if (read == 0)
break;
response.OutputStream.Write(buffer, 0, read);
}
response.End();
ms.Dispose();
imageStream.Dispose();
}
}

2、在HomeController.cs文件中添加Action,名称GetImage,并返回ImageResult

public ImageResizeResult GetImage(string image, int width, int height, bool noZooming = false)
{
return new ImageResizeResult(image, width, height, noZooming);
}

3、在home文件夹中Index.aspx中加上对图片的引用

<p>
<img src="/home/GetImage?image=tu.jpg&width=160&height=100"/>
<img src="/home/GetImage?image=tuyin.jpg&width=75&height=20" />
<img src="/home/GetImage?image=tuyin.jpg&width=100&height=100&noZooming=true" />
</p>

最后访问http://localhost:13811/home/就可看到效果

你可能感兴趣的:(asp.net)