模拟QQ心情图片上传预览
出于安全性能的考虑,目前js端不支持获取本地图片进行预览,正好在做一款类似于QQ心情的发布框,找了不少jquery插件,没几个能满足需求,因此自己使用SWFuplad来实现这个图片上传预览。
先粘上以下插件,在别的图片上传功能说不定各位能用的上。
1、jQuery File Upload
Demo地址:http://blueimp.github.io/jQuery-File-Upload/
优点是使用jquery进行图片的异步上传,可控性好,可根据自己的需求任意定制;
缺点是在IE9等一些浏览器中,不支持图片预览,图片选择框中不支持多文件选择(这点是我抛弃它的原因);
1、图片的上传预览(先将图片上传至服务器,然后再返回地址预览,目前抛开html5比较靠谱的预览方式)
1、Thumbnail.cs
public class Thumbnial
{
/// <summary>
/// 生成缩略图
/// </summary>
/// <param name="imgSource">原图片</param>
/// <param name="newWidth">缩略图宽度</param>
/// <param name="newHeight">缩略图高度</param>
/// <param name="isCut">是否裁剪(以中心点)</param>
/// <returns></returns>
public static Image GetThumbnail(System.Drawing.Image imgSource, int newWidth, int newHeight, bool isCut)
{
int rWidth = 0; // 等比例缩放后的宽度
int rHeight = 0; // 等比例缩放后的高度
int sWidth = imgSource.Width; // 原图片宽度
int sHeight = imgSource.Height; // 原图片高度
double wScale = (double)sWidth / newWidth; // 宽比例
double hScale = (double)sHeight / newHeight; // 高比例
double scale = wScale < hScale ? wScale : hScale;
rWidth = (int)Math.Floor(sWidth / scale);
rHeight = (int)Math.Floor(sHeight / scale);
Bitmap thumbnail = new Bitmap(rWidth, rHeight);
try
{
// 如果是截取原图,并且原图比例小于所要截取的矩形框,那么保留原图
if (!isCut && scale <= 1)
{
return imgSource;
} using (Graphics tGraphic = Graphics.FromImage(thumbnail))
{
tGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
Rectangle rect = new Rectangle(0, 0, rWidth, rHeight);
Rectangle rectSrc = new Rectangle(0, 0, sWidth, sHeight);
tGraphic.DrawImage(imgSource, rect, rectSrc, GraphicsUnit.Pixel);
} if (!isCut)
{
return thumbnail;
}
else
{
int xMove = 0; // 向右偏移(裁剪)
int yMove = 0; // 向下偏移(裁剪)
xMove = (rWidth - newWidth) / 2;
yMove = (rHeight - newHeight) / 2;
Bitmap final_image = new Bitmap(newWidth, newHeight);
using (Graphics fGraphic = Graphics.FromImage(final_image))
{
fGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; /* new way */
Rectangle rect1 = new Rectangle(0, 0, newWidth, newHeight);
Rectangle rectSrc1 = new Rectangle(xMove, yMove, newWidth, newHeight);
fGraphic.DrawImage(thumbnail, rect1, rectSrc1, GraphicsUnit.Pixel);
} thumbnail.Dispose(); return final_image;
}
}
catch (Exception e)
{
return new Bitmap(newWidth, newHeight);
}
}
}
2、图片上传处理程序Upload.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing; namespace Mood
{
/// <summary>
/// Upload 的摘要说明
/// </summary>
public class Upload : IHttpHandler
{
Image thumbnail; public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
string id = System.Guid.NewGuid().ToString();
HttpPostedFile jpeg_image_upload = context.Request.Files["Filedata"];
Image original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);
original_image.Save(System.Web.HttpContext.Current.Server.MapPath("~/Files/" + id + ".jpg"));
int target_width = 200;
int target_height = 150;
string path = "Files/Files200/" + id + ".jpg";
string saveThumbnailPath = System.Web.HttpContext.Current.Server.MapPath("~/" + path);
thumbnail = Thumbnial.GetThumbnail(original_image, target_width, target_height, true);
thumbnail.Save(saveThumbnailPath);
context.Response.Write(path);
}
catch (Exception e)
{
// If any kind of error occurs return a 500 Internal Server error
context.Response.StatusCode = 500;
context.Response.Write("上传过程中出现错误!");
}
finally
{
if (thumbnail != null)
{
thumbnail.Dispose();
}
}
} public bool IsReusable
{
get
{
return false;
}
}
}
}
3、前台界面Mood.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Mood.aspx.cs" Inherits="Mood.Mood" %> <!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">
<script src="SwfUpload/swfupload.js" type="text/javascript"></script>
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<link href="Style/Mood.css" rel="stylesheet" type="text/css" />
<title></title>
<script type="text/javascript">
$().ready(function () {
SetSwf();
$("#btnReply").click(function () {
$("#divImgs").hide();
});
}); var swfu;
function SetSwf() {
swfu = new SWFUpload({
// Backend Settings
upload_url: "Upload.ashx",
// File Upload Settings
file_size_limit: "20 MB",
file_types: "*.jpg;*.png;*jpeg;*bmp",
file_types_description: "JPG;PNG;JPEG;BMP",
file_upload_limit: "0", // Zero means unlimited
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: "/Style/Image/4-16.png",
button_placeholder_id: "divBtn",
button_width: 26,
button_height: 26, // Flash Settings
flash_url: "/swfupload/swfupload.swf", custom_settings: {
upload_target: "divFileProgressContainer"
}, // Debug Settings
debug: false
});
} // 文件校验
function fileQueueError(file, errorCode, message) {
try {
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
alert("上传文件有错误!");
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
alert("上传文件超过限制(20M)!");
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
default:
alert("文件出现错误!");
break;
}
} catch (ex) {
this.debug(ex);
} } // 文件选择完毕时触发
function fileDialogComplete(numFilesSelected, numFilesQueued) {
try {
if (numFilesQueued > 0) {
$("#divImgs").show();
for (var i = 0; i < numFilesQueued; i++) {
$("#ulUpload").append('<li id="li' + i + '"><img class="imgload" src="/style/image/loading.gif" alt="" /></li>');
} this.startUpload();
}
} catch (ex) {
this.debug(ex);
}
} // 滚动条的处理方法 暂时没写
function uploadProgress(file, bytesLoaded) {
} // 每个文件上传成功后的处理
function uploadSuccess(file, serverData) {
try {
var index = file.id.substr(file.id.lastIndexOf('_') + 1);
$("#li" + index).html("");
$("#li" + index).html('<img src="' + serverData + '" alt=""/>');
index++; } catch (ex) {
this.debug(ex);
}
} // 上传完成后,触发下一个文件的上传
function uploadComplete(file) {
try {
if (this.getStats().files_queued > 0) {
this.startUpload();
}
} catch (ex) {
this.debug(ex);
}
} // 单个文件上传错误时处理
function uploadError(file, errorCode, message) {
var imageName = "imgerror.png";
try {
var index = file.id.substr(file.id.lastIndexOf('_') + 1);
$("#li" + index).html("");
$("#li" + index).html('<img src="/style/image/imgerror.png" alt=""/>');
index++;
} catch (ex3) {
this.debug(ex3);
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="width: 600px;">
<div class="divTxt">
文本框
</div>
<div style="height: 30px; line-height: 30px;">
<div id="divBtn" style="float: left; width: 26px; height: 26px;">
</div>
<div style="float: right;">
<input id="btnReply" type="button" value="发表" />
</div>
</div>
<div id="divImgs" style="border: 1px solid #cdcdcd; display: none;">
<div>
上传图片</div>
<ul id="ulUpload" class="ulUpload">
</ul>
</div>
</div>
</form>
</body>
</html>
使用Vs2010开发,以下为项目源码地址:http://download.csdn.net/detail/wuwo333/5944249
模拟QQ心情图片上传预览的更多相关文章
- 兼容好的JS图片上传预览代码
转 : http://www.codefans.net/articles/1395.shtml 兼容好的JS图片上传预览代码 (谷歌,IE11) <html xmlns="http:/ ...
- Jquery图片上传预览效果
uploadPreview.js jQuery.fn.extend({ uploadPreview: function (opts) { var _self = this, _this = $(thi ...
- [前端 4] 使用Js实现图片上传预览
导读:今天做图片上传预览,刚开始的做法是,先将图片上传到Nginx,然后重新加载页面才能看到这个图片.在这个过程中,用户一直都看不到自己上传的文件是什么样子.Ps:我发现我真的有强迫症了,都告诉我说不 ...
- Javascript之图片上传预览
使用Javascript之图片上传预览,我们无需上传到服务器中,兼容所有浏览器. 关键方法是使用微软库filter:progid:DXImageTransform.Microsoft.AlphaIma ...
- HTML5 图片上传预览
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="utf-8& ...
- ASP.NET工作笔记之一:图片上传预览及无刷新上传
转自:http://www.cnblogs.com/sibiyellow/archive/2012/04/27/jqueryformjs.html 最近项目里面涉及到无刷新上传图片的功能,其实也就是上 ...
- php 图片上传预览(转)
网上找的图片上传预览: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http:/ ...
- js实现图片上传预览及进度条
原文js实现图片上传预览及进度条 最近在做图片上传的时候,由于产品设计的比较fashion,上网找了比较久还没有现成的,因此自己做了一个,实现的功能如下: 1:去除浏览器<input type= ...
- html 图片上传预览
Html5 upload img 2012年12月27日 20:36 <!DOCTYPE HTML> <html> <head> <meta http-equ ...
随机推荐
- 在(Raspberry Pi)树莓派上安装NodeJS
本文主讲如何在树莓派3B上安装node.js 环境描述1. 树莓派安装了`2016-11-25-raspbian-jessie-lite`(PS:在此版本的镜像中,默认禁用了ssh,在烧录好镜像之后, ...
- Highmaps网页图表教程之绘图区显示标签显示数据标签定位
Highmaps网页图表教程之绘图区显示标签显示数据标签定位 Highmaps数据标签定位 由于数据标签是和节点一一对应,所以数据标签是依据节点位置进行定位的.本节详细讲解如何对数据标签进行定位. H ...
- 下拉框搜索插件chosen
{% load staticfiles %} <!DOCTYPE html> <html lang="en"> <head> <meta ...
- window下完全删除nodejs
1.从卸载程序卸载程序和功能. 2.重新启动(或者您可能会从任务管理器中杀死所有与节点相关的进程). 3.寻找这些文件夹并删除它们(及其内容)(如果还有).根据您安装的版本,UAC设置和CPU架构,这 ...
- Django的orm中get和filter的不同
Django的orm框架对于业务复杂度不是很高的应用来说还是不错的,写起来很方面,用起来也简单.对于新手来说查询操作中最长用的两个方法get和filter有时候一不注意就会犯下一些小错误.那么今天就来 ...
- 腾讯云服务器无法ssh登陆问题
SSH 登录时出现如下错误:Permission denied, please try again 解决:腾讯云主机控制台登录,先要设置root密码 修改 /etc/ssh/sshd_config 中 ...
- Redis Cluster笔记
Redis Cluster .0搭建与使用 介绍: 特性:使用数据分片(sharding)而非一致性哈希(consistency hashing)来实现: 一个 Redis 集群包含 个哈希槽(has ...
- POJ 2356 Find a multiple 抽屉原理
从POJ 2356来体会抽屉原理的妙用= =! 题意: 给你一个n,然后给你n个数,让你输出一个数或者多个数,让这些数的和能够组成n: 先输出一个数,代表有多少个数的和,然后再输出这些数: 题解: 首 ...
- python循环与判断
学习一门新的语言最重要的就是练习. 一.脚本需求: 编写登陆接口 输入用户名密码 认证成功后显示欢迎信息 输错三次后锁定 二.脚本流程图: 写代码之前画个流程图总是好的,可以让你理清思路,避免写着写着 ...
- bootstrap字体图标不正常显示的原因
本地引入bootstrap.css文件,使用https://v3.bootcss.com/components/站点 字体图标 时不能正常显示,换成 bootstrap 官网的 cdn 链接却能正常显 ...