//上传页面
代码
代码
代码
代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="SwfuploadSample.aspx.cs"
Inherits="WebApp.SwfuploadSample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.Userupload
{
float: left;
list-style: none;
padding-left: 310px;
}
.Userupload li
{
color: #666666;
display: block;
text-align: left;
vertical-align: middle;
}
</style>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript" src="/swfupload/js/swfupload.js"></script>
<script type="text/javascript" src="/swfupload/js/handlers.js" charset="gb2312"></script>
<script type="text/javascript">
var swfu;
$("#divAdd").ready(function() {
var fileLmt = parseInt('<%= System.Configuration.ConfigurationManager.AppSettings["FileSize"]%>');
if (fileLmt > 1024)
fileLmt = parseInt(fileLmt / 1024);
else
fileLmt = 1;
$("#lblFileSize").html(fileLmt);
swfu = new SWFUpload({
// Backend Settings
upload_url: "/swfupload/handler/uploadHandler.aspx",
post_params: {
"ASPSESSID": "<%=Session.SessionID %>",
"AUTHID": "<%=ClientAUTHID%>"
},
// File Upload Settings
file_size_limit: fileLmt + " MB",
file_types: "*.jpg;*.gif;*.bmp;*.png;",
file_types_description: "JPG Images",
file_upload_limit: 1, // Zero means unlimited
// Event Handler Settings - these functions as defined in Handlers.js
// The handlers are not part of SWFUpload but are part of my website and control how
// my website reacts to the SWFUpload events.
file_queued_handler: fileQueued, //选择过文件后,把文件放入队列后,所触发的事件
file_queue_error_handler: fileQueueError,
file_dialog_complete_handler: fileDialogComplete,
upload_progress_handler: uploadProgress,
upload_error_handler: uploadError,
upload_success_handler: uploadSuccess,
upload_complete_handler: uploadComplete,
// Button settings
button_image_url: "/swfupload/images/addimg.png",
button_placeholder_id: "selectImg",
button_width: 56,
button_height: 27,
button_text_style: "color: #000000; font-size: 10pt;",
// Flash Settings
flash_url: "/swfupload/swfupload.swf", // Relative to this file
custom_settings: {
upload_target: "divFileProgressContainer"
},
// Debug Settings
debug: false
});
});
function UploadImg() {
var check = jQuery.formValidator.pageIsValid();
if (check) {
var lnk = $("#aSubmit")[0];
lnk.disabled = true;
lnk.removeAttribute('href');
$("form:first").submit();
}
}
function GotoAddPage() {
location.href = "/addphoto.html";
}
function uploadSuccess(file, serverData) {
try {
addImage("/swfupload/handler/thumbnailHandler.aspx?id=" + serverData);
var progress = new FileProgress(file, this.customSettings.upload_target);
progress.setStatus("ThumbnailFile Created.");
progress.toggleCancel(false);
$("#<%=hfPhotoId.ClientID %>").val(serverData);
} catch (ex) {
this.debug(ex);
}
}
function addImage(src) {
var imgCache = new Image(150, 150);
imgCache.src = src;
$("#liImgShow").append(imgCache);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="AlbumContent" id="divAdd" style="min-height: 500px;">
<!--专辑选择-->
<div class="AlbumUpLoadType">
<span style="float: left">所属专辑:</span><span style="float: left; margin-left: 5px;">
<asp:DropDownList ID="ddlAlbumList" runat="server" CssClass="AlbumUpLoadTypeDrop">
</asp:DropDownList>
</span><span style="float: left; width: 100px; display: inline; display: block;">[<a
href="javascript:MaskDialog.show();">创建新专辑</a>]</span>
</div>
<div class="AlbumUpLoadType">
照片名称:<input id="photoname" name="photoname" type="text" style="border: 1px solid #7F9DB9;" /><span
id="photonameTip"></span></div>
<!--上传控件-->
<div id="divUploadBody">
<ul class="Userupload">
<li>
<div style="height: 20px;">
请选择图片,文件小于<label id="lblFileSize"></label>M
<label id="lblPhotoCnt">
</label>
</div>
</li>
<li style="padding-top: 10px; padding-left: 10px;"><span id="selectImg"></span><span
id="<%=hfPhotoId.ClientID %>Tip"></span>
<br />
<div id="divFileProgressContainer">
</div>
<div id="thumbnails">
</div>
</li>
<li style="padding-top: 10px;" id="liImgShow"></li>
<li style="padding-top: 10px;">
<div class="AlbumButtBg" style="margin: auto; float: none;">
<input id="aSubmit" class="buttonUpSmall" value="上传图片" onmousedown="this.className='buttonDownSmall';"
onmouseup="this.className='buttonUpSmall';" type="button" onclick="javascript:UploadImg();" />
</div>
</li>
</ul>
</div>
<input type="hidden" id="hfPhotoId" runat="server" />
<div class="c">
</div>
</div>
</form>
</body>
</html>
Inherits="WebApp.SwfuploadSample" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.Userupload
{
float: left;
list-style: none;
padding-left: 310px;
}
.Userupload li
{
color: #666666;
display: block;
text-align: left;
vertical-align: middle;
}
</style>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript" src="/swfupload/js/swfupload.js"></script>
<script type="text/javascript" src="/swfupload/js/handlers.js" charset="gb2312"></script>
<script type="text/javascript">
var swfu;
$("#divAdd").ready(function() {
var fileLmt = parseInt('<%= System.Configuration.ConfigurationManager.AppSettings["FileSize"]%>');
if (fileLmt > 1024)
fileLmt = parseInt(fileLmt / 1024);
else
fileLmt = 1;
$("#lblFileSize").html(fileLmt);
swfu = new SWFUpload({
// Backend Settings
upload_url: "/swfupload/handler/uploadHandler.aspx",
post_params: {
"ASPSESSID": "<%=Session.SessionID %>",
"AUTHID": "<%=ClientAUTHID%>"
},
// File Upload Settings
file_size_limit: fileLmt + " MB",
file_types: "*.jpg;*.gif;*.bmp;*.png;",
file_types_description: "JPG Images",
file_upload_limit: 1, // Zero means unlimited
// Event Handler Settings - these functions as defined in Handlers.js
// The handlers are not part of SWFUpload but are part of my website and control how
// my website reacts to the SWFUpload events.
file_queued_handler: fileQueued, //选择过文件后,把文件放入队列后,所触发的事件
file_queue_error_handler: fileQueueError,
file_dialog_complete_handler: fileDialogComplete,
upload_progress_handler: uploadProgress,
upload_error_handler: uploadError,
upload_success_handler: uploadSuccess,
upload_complete_handler: uploadComplete,
// Button settings
button_image_url: "/swfupload/images/addimg.png",
button_placeholder_id: "selectImg",
button_width: 56,
button_height: 27,
button_text_style: "color: #000000; font-size: 10pt;",
// Flash Settings
flash_url: "/swfupload/swfupload.swf", // Relative to this file
custom_settings: {
upload_target: "divFileProgressContainer"
},
// Debug Settings
debug: false
});
});
function UploadImg() {
var check = jQuery.formValidator.pageIsValid();
if (check) {
var lnk = $("#aSubmit")[0];
lnk.disabled = true;
lnk.removeAttribute('href');
$("form:first").submit();
}
}
function GotoAddPage() {
location.href = "/addphoto.html";
}
function uploadSuccess(file, serverData) {
try {
addImage("/swfupload/handler/thumbnailHandler.aspx?id=" + serverData);
var progress = new FileProgress(file, this.customSettings.upload_target);
progress.setStatus("ThumbnailFile Created.");
progress.toggleCancel(false);
$("#<%=hfPhotoId.ClientID %>").val(serverData);
} catch (ex) {
this.debug(ex);
}
}
function addImage(src) {
var imgCache = new Image(150, 150);
imgCache.src = src;
$("#liImgShow").append(imgCache);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="AlbumContent" id="divAdd" style="min-height: 500px;">
<!--专辑选择-->
<div class="AlbumUpLoadType">
<span style="float: left">所属专辑:</span><span style="float: left; margin-left: 5px;">
<asp:DropDownList ID="ddlAlbumList" runat="server" CssClass="AlbumUpLoadTypeDrop">
</asp:DropDownList>
</span><span style="float: left; width: 100px; display: inline; display: block;">[<a
href="javascript:MaskDialog.show();">创建新专辑</a>]</span>
</div>
<div class="AlbumUpLoadType">
照片名称:<input id="photoname" name="photoname" type="text" style="border: 1px solid #7F9DB9;" /><span
id="photonameTip"></span></div>
<!--上传控件-->
<div id="divUploadBody">
<ul class="Userupload">
<li>
<div style="height: 20px;">
请选择图片,文件小于<label id="lblFileSize"></label>M
<label id="lblPhotoCnt">
</label>
</div>
</li>
<li style="padding-top: 10px; padding-left: 10px;"><span id="selectImg"></span><span
id="<%=hfPhotoId.ClientID %>Tip"></span>
<br />
<div id="divFileProgressContainer">
</div>
<div id="thumbnails">
</div>
</li>
<li style="padding-top: 10px;" id="liImgShow"></li>
<li style="padding-top: 10px;">
<div class="AlbumButtBg" style="margin: auto; float: none;">
<input id="aSubmit" class="buttonUpSmall" value="上传图片" onmousedown="this.className='buttonDownSmall';"
onmouseup="this.className='buttonUpSmall';" type="button" onclick="javascript:UploadImg();" />
</div>
</li>
</ul>
</div>
<input type="hidden" id="hfPhotoId" runat="server" />
<div class="c">
</div>
</div>
</form>
</body>
</html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApp {
public partial class SwfuploadSample : System.Web.UI.Page {
public string ClientAUTHID {
get {
string strAuthid = "";
if (Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName] != null) {
strAuthid = Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName].Value;
}
return strAuthid;
}
}
protected void Page_Load(object sender, EventArgs e) {
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApp {
public partial class SwfuploadSample : System.Web.UI.Page {
public string ClientAUTHID {
get {
string strAuthid = "";
if (Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName] != null) {
strAuthid = Request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName].Value;
}
return strAuthid;
}
}
protected void Page_Load(object sender, EventArgs e) {
}
}
}
//缩略图类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApp.swfupload.handler
{
public class ThumbnailFile
{
public ThumbnailFile(string id, byte[] data)
{
this.ID = id;
this.Data = data;
}
private string id;
public string ID
{
get
{
return this.id;
}
set
{
this.id = value;
}
}
public int width { get; set; }
public int height { get; set; }
private string filename;
public string FileName
{
get
{
return filename;
}
set
{
filename = value;
}
}
private byte[] thumbnail_data;
public byte[] Data
{
get
{
return this.thumbnail_data;
}
set
{
this.thumbnail_data = value;
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApp.swfupload.handler
{
public class ThumbnailFile
{
public ThumbnailFile(string id, byte[] data)
{
this.ID = id;
this.Data = data;
}
private string id;
public string ID
{
get
{
return this.id;
}
set
{
this.id = value;
}
}
public int width { get; set; }
public int height { get; set; }
private string filename;
public string FileName
{
get
{
return filename;
}
set
{
filename = value;
}
}
private byte[] thumbnail_data;
public byte[] Data
{
get
{
return this.thumbnail_data;
}
set
{
this.thumbnail_data = value;
}
}
}
}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
namespace WebApp.swfupload.handler
{
public partial class ThumbnailHandler : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string file_id = Request.QueryString["id"] as string;
if (file_id == null)
{
Response.StatusCode = 404;
Response.Write("Not Found");
Response.End();
return;
}
List<ThumbnailFile> thumbnails = Session["file_info"] as List<ThumbnailFile>;
if (thumbnails == null)
{
Response.StatusCode = 404;
Response.Write("Not Found");
Response.End();
return;
}
foreach (ThumbnailFile thumb in thumbnails)
{
if (thumb.ID == file_id)
{
Response.ContentType = "image/jpeg";
Response.BinaryWrite(thumb.Data);
Response.End();
return;
}
}
// If we reach here then we didn't find the file id so return 404
Response.StatusCode = 404;
Response.Write("Not Found");
Response.End();
}
}
}
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
namespace WebApp.swfupload.handler
{
public partial class ThumbnailHandler : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string file_id = Request.QueryString["id"] as string;
if (file_id == null)
{
Response.StatusCode = 404;
Response.Write("Not Found");
Response.End();
return;
}
List<ThumbnailFile> thumbnails = Session["file_info"] as List<ThumbnailFile>;
if (thumbnails == null)
{
Response.StatusCode = 404;
Response.Write("Not Found");
Response.End();
return;
}
foreach (ThumbnailFile thumb in thumbnails)
{
if (thumb.ID == file_id)
{
Response.ContentType = "image/jpeg";
Response.BinaryWrite(thumb.Data);
Response.End();
return;
}
}
// If we reach here then we didn't find the file id so return 404
Response.StatusCode = 404;
Response.Write("Not Found");
Response.End();
}
}
}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections.Generic;
namespace WebApp.swfupload.handler {
public partial class UploadHandler : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (Request["bwidth"] != null || Request["lwidth"] != null || Request["bheight"] != null || Request["lheight"] != null) {
CreateRatingImg();
return;
}
if (Request["width"] != null) {
CreateThumbnail();
return;
}
System.Drawing.Image imgOrigin = null;
MemoryStream ms = null;
try {
// Get the data
HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];
// Retrieve the uploaded image
imgOrigin = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);
// Calculate the new width and height
int width = imgOrigin.Width;
int height = imgOrigin.Height;
// Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo)
ms = new MemoryStream();
imgOrigin.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
// Store the data in my custom ThumbnailFile object
string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
ThumbnailFile thumb = new ThumbnailFile(thumbnail_id, ms.GetBuffer());
// Put it all in the Session (initialize the session if necessary)
List<ThumbnailFile> thumbnails = Session["file_info"] as List<ThumbnailFile>;
if (thumbnails == null) {
thumbnails = new List<ThumbnailFile>();
Session["file_info"] = thumbnails;
}
thumb.height = height;
thumb.width = width;
thumbnails.Add(thumb);
thumb.FileName = jpeg_image_upload.FileName;
Response.StatusCode = 200;
Response.Write(thumbnail_id);
}
catch {
// If any kind of error occurs return a 500 Internal Server error
Response.StatusCode = 500;
Response.Write("An error occured");
Response.End();
}
finally {
if (imgOrigin != null) imgOrigin.Dispose();
if (ms != null) ms.Close();
Response.End();
}
}
/// <summary>
/// 根据request的宽度、高度限制参数生成图片
/// </summary>
private void CreateRatingImg() {
ImageHelp imgHelp = new ImageHelp();
HttpPostedFile uploadImg = Request.Files["Filedata"];
int maxW = 0, maxH = 0, minW = 0, minH = 0;
if (Request["bwidth"] != null) {
int.TryParse(Request["bwidth"], out maxW);
}
if (!string.IsNullOrEmpty(Request["bheight"]))
int.TryParse(Request["bheight"], out maxH);
if (!string.IsNullOrEmpty(Request["lwidth"]))
int.TryParse(Request["lwidth"], out minW);
if (!string.IsNullOrEmpty(Request["lheight"]))
int.TryParse(Request["lheight"], out minH);
if (minH > maxH || minW > maxW) {
Response.StatusCode = 500;
Response.Write("An error occured");
Response.End();
return;
}
int targetH = 0, targetW = 0;
minW = minW >= 50 ? minW : 50;
minH = minH >= 50 ? minH : 50;
System.Drawing.Image imgOrigin = null;
MemoryStream ms = null;
try {
imgOrigin = System.Drawing.Image.FromStream(uploadImg.InputStream);
if (maxW < 50)
maxW = imgOrigin.Width;
if (maxH < 50)
maxH = imgOrigin.Height;
//根据图片尺寸限制确定目标图片缩放尺寸
targetW = imgOrigin.Width > maxW ? maxW : imgOrigin.Width;
targetH = imgOrigin.Height > maxH ? maxH : imgOrigin.Height;
targetW = targetW < minW ? minW : targetW;
targetH = targetH < minH ? minH : targetH;
if (imgOrigin.Height == targetH && imgOrigin.Width == targetW) {
ms = new MemoryStream();
imgOrigin.Save(ms, imgHelp.GetImageType(System.IO.Path.GetExtension(uploadImg.FileName)));
}
else {
ms = imgHelp.MakeThumbnail(uploadImg.InputStream, uploadImg.FileName, targetW, targetH);
}
// Store the data in my custom ThumbnailFile object
string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
ThumbnailFile thumb = new ThumbnailFile(thumbnail_id, ms.GetBuffer());
// Put it all in the Session (initialize the session if necessary)
List<ThumbnailFile> thumbnails = Session["file_info"] as List<ThumbnailFile>;
if (thumbnails == null) {
thumbnails = new List<ThumbnailFile>();
Session["file_info"] = thumbnails;
}
thumb.height = targetH;
thumb.width = targetW;
thumbnails.Add(thumb);
thumb.FileName = uploadImg.FileName;
Response.StatusCode = 200;
Response.Write(thumbnail_id);
}
catch {
Response.StatusCode = 500;
Response.Write("An error occured");
Response.End();
}
finally {
if (imgOrigin != null) imgOrigin.Dispose();
if (ms != null) ms.Close();
Response.End();
}
}
private void CreateThumbnail() {
System.Drawing.Image thumbnail_image = null;
System.Drawing.Image imgOrigin = null;
System.Drawing.Bitmap final_image = null;
System.Drawing.Graphics graphic = null;
MemoryStream ms = null;
try {
// Get the data
HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];
// Retrieve the uploaded image
imgOrigin = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);
// Calculate the new width and height
int width = imgOrigin.Width;
int height = imgOrigin.Height;
int target_width = 0;
int target_height = 0;
int new_width, new_height;
if (Request["width"] != null)
int.TryParse(Request["width"], out target_width);
if (Request["height"] != null)
int.TryParse(Request["height"], out target_height);
if (target_width == 0)
target_width = 100;
if (target_height == 0)
target_height = 100;
float target_ratio = (float)target_width / (float)target_height;
float image_ratio = (float)width / (float)height;
if (target_ratio > image_ratio) {
new_height = target_height;
new_width = (int)Math.Floor(image_ratio * (float)target_height);
}
else {
new_height = (int)Math.Floor((float)target_width / image_ratio);
new_width = target_width;
}
new_width = new_width > target_width ? target_width : new_width;
new_height = new_height > target_height ? target_height : new_height;
// Create the thumbnail
// We don't have to create a ThumbnailFile since the DrawImage method will resize, but the GetThumbnailImage looks better
// I've read about a problem with GetThumbnailImage. If a jpeg has an embedded thumbnail it will use and resize that which
// can result in a tiny 40x40 thumbnail being stretch up to our target size
final_image = new System.Drawing.Bitmap(target_width, target_height);
graphic = System.Drawing.Graphics.FromImage(final_image);
graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, target_width, target_height));
int paste_x = (target_width - new_width) / 2;
int paste_y = (target_height - new_height) / 2;
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.DrawImage(imgOrigin, paste_x, paste_y, new_width, new_height);
// Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo)
ms = new MemoryStream();
final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
// Store the data in my custom ThumbnailFile object
string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
ThumbnailFile thumb = new ThumbnailFile(thumbnail_id, ms.GetBuffer());
// Put it all in the Session (initialize the session if necessary)
List<ThumbnailFile> thumbnails = Session["file_info"] as List<ThumbnailFile>;
if (thumbnails == null) {
thumbnails = new List<ThumbnailFile>();
Session["file_info"] = thumbnails;
}
thumb.height = new_height;
thumb.width = new_width;
thumbnails.Add(thumb);
thumb.FileName = jpeg_image_upload.FileName;
Response.StatusCode = 200;
Response.Write(thumbnail_id);
}
catch {
// If any kind of error occurs return a 500 Internal Server error
Response.StatusCode = 500;
Response.Write("An error occured");
Response.End();
}
finally {
// Clean up
if (final_image != null) final_image.Dispose();
if (graphic != null) graphic.Dispose();
if (imgOrigin != null) imgOrigin.Dispose();
if (thumbnail_image != null) thumbnail_image.Dispose();
if (ms != null) ms.Close();
Response.End();
}
}
}
}
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections.Generic;
namespace WebApp.swfupload.handler {
public partial class UploadHandler : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
if (Request["bwidth"] != null || Request["lwidth"] != null || Request["bheight"] != null || Request["lheight"] != null) {
CreateRatingImg();
return;
}
if (Request["width"] != null) {
CreateThumbnail();
return;
}
System.Drawing.Image imgOrigin = null;
MemoryStream ms = null;
try {
// Get the data
HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];
// Retrieve the uploaded image
imgOrigin = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);
// Calculate the new width and height
int width = imgOrigin.Width;
int height = imgOrigin.Height;
// Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo)
ms = new MemoryStream();
imgOrigin.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
// Store the data in my custom ThumbnailFile object
string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
ThumbnailFile thumb = new ThumbnailFile(thumbnail_id, ms.GetBuffer());
// Put it all in the Session (initialize the session if necessary)
List<ThumbnailFile> thumbnails = Session["file_info"] as List<ThumbnailFile>;
if (thumbnails == null) {
thumbnails = new List<ThumbnailFile>();
Session["file_info"] = thumbnails;
}
thumb.height = height;
thumb.width = width;
thumbnails.Add(thumb);
thumb.FileName = jpeg_image_upload.FileName;
Response.StatusCode = 200;
Response.Write(thumbnail_id);
}
catch {
// If any kind of error occurs return a 500 Internal Server error
Response.StatusCode = 500;
Response.Write("An error occured");
Response.End();
}
finally {
if (imgOrigin != null) imgOrigin.Dispose();
if (ms != null) ms.Close();
Response.End();
}
}
/// <summary>
/// 根据request的宽度、高度限制参数生成图片
/// </summary>
private void CreateRatingImg() {
ImageHelp imgHelp = new ImageHelp();
HttpPostedFile uploadImg = Request.Files["Filedata"];
int maxW = 0, maxH = 0, minW = 0, minH = 0;
if (Request["bwidth"] != null) {
int.TryParse(Request["bwidth"], out maxW);
}
if (!string.IsNullOrEmpty(Request["bheight"]))
int.TryParse(Request["bheight"], out maxH);
if (!string.IsNullOrEmpty(Request["lwidth"]))
int.TryParse(Request["lwidth"], out minW);
if (!string.IsNullOrEmpty(Request["lheight"]))
int.TryParse(Request["lheight"], out minH);
if (minH > maxH || minW > maxW) {
Response.StatusCode = 500;
Response.Write("An error occured");
Response.End();
return;
}
int targetH = 0, targetW = 0;
minW = minW >= 50 ? minW : 50;
minH = minH >= 50 ? minH : 50;
System.Drawing.Image imgOrigin = null;
MemoryStream ms = null;
try {
imgOrigin = System.Drawing.Image.FromStream(uploadImg.InputStream);
if (maxW < 50)
maxW = imgOrigin.Width;
if (maxH < 50)
maxH = imgOrigin.Height;
//根据图片尺寸限制确定目标图片缩放尺寸
targetW = imgOrigin.Width > maxW ? maxW : imgOrigin.Width;
targetH = imgOrigin.Height > maxH ? maxH : imgOrigin.Height;
targetW = targetW < minW ? minW : targetW;
targetH = targetH < minH ? minH : targetH;
if (imgOrigin.Height == targetH && imgOrigin.Width == targetW) {
ms = new MemoryStream();
imgOrigin.Save(ms, imgHelp.GetImageType(System.IO.Path.GetExtension(uploadImg.FileName)));
}
else {
ms = imgHelp.MakeThumbnail(uploadImg.InputStream, uploadImg.FileName, targetW, targetH);
}
// Store the data in my custom ThumbnailFile object
string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
ThumbnailFile thumb = new ThumbnailFile(thumbnail_id, ms.GetBuffer());
// Put it all in the Session (initialize the session if necessary)
List<ThumbnailFile> thumbnails = Session["file_info"] as List<ThumbnailFile>;
if (thumbnails == null) {
thumbnails = new List<ThumbnailFile>();
Session["file_info"] = thumbnails;
}
thumb.height = targetH;
thumb.width = targetW;
thumbnails.Add(thumb);
thumb.FileName = uploadImg.FileName;
Response.StatusCode = 200;
Response.Write(thumbnail_id);
}
catch {
Response.StatusCode = 500;
Response.Write("An error occured");
Response.End();
}
finally {
if (imgOrigin != null) imgOrigin.Dispose();
if (ms != null) ms.Close();
Response.End();
}
}
private void CreateThumbnail() {
System.Drawing.Image thumbnail_image = null;
System.Drawing.Image imgOrigin = null;
System.Drawing.Bitmap final_image = null;
System.Drawing.Graphics graphic = null;
MemoryStream ms = null;
try {
// Get the data
HttpPostedFile jpeg_image_upload = Request.Files["Filedata"];
// Retrieve the uploaded image
imgOrigin = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);
// Calculate the new width and height
int width = imgOrigin.Width;
int height = imgOrigin.Height;
int target_width = 0;
int target_height = 0;
int new_width, new_height;
if (Request["width"] != null)
int.TryParse(Request["width"], out target_width);
if (Request["height"] != null)
int.TryParse(Request["height"], out target_height);
if (target_width == 0)
target_width = 100;
if (target_height == 0)
target_height = 100;
float target_ratio = (float)target_width / (float)target_height;
float image_ratio = (float)width / (float)height;
if (target_ratio > image_ratio) {
new_height = target_height;
new_width = (int)Math.Floor(image_ratio * (float)target_height);
}
else {
new_height = (int)Math.Floor((float)target_width / image_ratio);
new_width = target_width;
}
new_width = new_width > target_width ? target_width : new_width;
new_height = new_height > target_height ? target_height : new_height;
// Create the thumbnail
// We don't have to create a ThumbnailFile since the DrawImage method will resize, but the GetThumbnailImage looks better
// I've read about a problem with GetThumbnailImage. If a jpeg has an embedded thumbnail it will use and resize that which
// can result in a tiny 40x40 thumbnail being stretch up to our target size
final_image = new System.Drawing.Bitmap(target_width, target_height);
graphic = System.Drawing.Graphics.FromImage(final_image);
graphic.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.Black), new System.Drawing.Rectangle(0, 0, target_width, target_height));
int paste_x = (target_width - new_width) / 2;
int paste_y = (target_height - new_height) / 2;
graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphic.DrawImage(imgOrigin, paste_x, paste_y, new_width, new_height);
// Store the thumbnail in the session (Note: this is bad, it will take a lot of memory, but this is just a demo)
ms = new MemoryStream();
final_image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
// Store the data in my custom ThumbnailFile object
string thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
ThumbnailFile thumb = new ThumbnailFile(thumbnail_id, ms.GetBuffer());
// Put it all in the Session (initialize the session if necessary)
List<ThumbnailFile> thumbnails = Session["file_info"] as List<ThumbnailFile>;
if (thumbnails == null) {
thumbnails = new List<ThumbnailFile>();
Session["file_info"] = thumbnails;
}
thumb.height = new_height;
thumb.width = new_width;
thumbnails.Add(thumb);
thumb.FileName = jpeg_image_upload.FileName;
Response.StatusCode = 200;
Response.Write(thumbnail_id);
}
catch {
// If any kind of error occurs return a 500 Internal Server error
Response.StatusCode = 500;
Response.Write("An error occured");
Response.End();
}
finally {
// Clean up
if (final_image != null) final_image.Dispose();
if (graphic != null) graphic.Dispose();
if (imgOrigin != null) imgOrigin.Dispose();
if (thumbnail_image != null) thumbnail_image.Dispose();
if (ms != null) ms.Close();
Response.End();
}
}
}
}