zl程序教程

您现在的位置是:首页 >  后端

当前栏目

asp.net中生成缩略图并添加版权实例代码

Net实例ASP代码 生成 添加 缩略图 版权
2023-06-13 09:15:11 时间

复制代码代码如下:


//定义image类的对象
Drawing.Imageimage,newimage;
//图片路径
protectedstringimagePath;
//图片类型
protectedstringimageType;
//图片名称
protectedstringimageName;
//提供一个回调方法,用于确定Image对象在执行生成缩略图操作时何时提前取消执行
//如果此方法确定GetThumbnailImage方法应提前停止执行,则返回true;否则返回false
System.Drawing.Image.GetThumbnailImageAbortcallb=null;

privatevoidsm_Click(objectsender,System.EventArgse)
{
stringmPath;

if(""!=File1.PostedFile.FileName)//File1为上传文件控件
{
imagePath=File1.PostedFile.FileName;
//取得图片类型
imageType=imagePath.Substring(imagePath.LastIndexOf(".")+1);
//取得图片名称
imageName=imagePath.Substring(imagePath.LastIndexOf("\\")+1);
//判断是否是JPG或者GIF图片,这里只是举个例子,并不一定必须是这两种图片
if("jpg"!=imageType&&"gif"!=imageType)
{
Response.Write("<scriptlanguage="javascript">alert("对不起!请您选择jpg或者gif格式的图片!");</script>");
return;
}
else
{
try
{
//建立虚拟路径
mPath=Server.MapPath("UploadFiles");
//保存到虚拟路径
File1.PostedFile.SaveAs(mPath+"\\"+imageName);

//显示原图,imageSource为图片控件
//imageSource.ImageUrl="UploadFiles/"+imageName;

//为上传的图片建立引用
image=System.Drawing.Image.FromFile(mPath+"\\"+imageName);
//生成缩略图
newimage=image.GetThumbnailImage(200,200,callb,newSystem.IntPtr());
//把缩略图保存到指定的虚拟路径
newimage.Save(Server.MapPath("UploadFiles")+"\\small"+imageName);
//释放image对象占用的资源
image.Dispose();
//释放newimage对象的资源
newimage.Dispose();
//显示缩略图

AddTextToImg("UploadFiles/"+"small"+imageName,"PicInfo");//在图片上加入信息说明
Image1.ImageUrl="UploadFiles/"+"small"+imageName;

Script.Alert("上传成功!");
}
catch
{
Script.Alert("上传失败!");
}

}//endelse
}

//在图片上加入自己的信息,
//AddTextToImg(physicPath,"PicInfo");
privatevoidAddTextToImg(stringfileName,stringtext)
{
//stringsss=MapPath(fileName);

if(!File.Exists(fileName)){
thrownewFileNotFoundException("Thefiledon"texist!");
}

//还需要判断文件类型是否为图像类型,这里就不赘述了

System.Drawing.Imageimage=System.Drawing.Image.FromFile(fileName);//MapPath(fileName));
Bitmapbitmap=newBitmap(image,image.Width,image.Height);
Graphicsg=Graphics.FromImage(bitmap);

floatfontSize=22.0f;//字体大小
floattextWidth=text.Length*fontSize;//文本的长度
//下面定义一个矩形区域,以后在这个矩形里画上白底黑字
floatrectX=0;
floatrectY=0;
floatrectWidth=text.Length*(fontSize+18);
floatrectHeight=fontSize+18;
//声明矩形域
RectangleFtextArea=newRectangleF(rectX,rectY,rectWidth,rectHeight);
Fontfont=newFont("宋体",fontSize);//定义字体
BrushwhiteBrush=newSolidBrush(Color.White);
BrushblackBrush=newSolidBrush(Color.Black);
g.FillRectangle(blackBrush,rectX,rectY,rectWidth,rectHeight);
g.DrawString(text,font,whiteBrush,textArea);
MemoryStreamms=newMemoryStream();
//保存为Jpg类型
bitmap.Save(ms,ImageFormat.Jpeg);

//输出处理后的图像,这里为了演示方便,我将图片显示在页面中了
/**//*Response.Clear();
Response.ContentType="image/jpeg";
Response.BinaryWrite(ms.ToArray());
*/
FileStreamfs=newFileStream(fileName,FileMode.OpenOrCreate);//.CreateNew);
fs.Write(ms.ToArray(),0,ms.ToArray().Length);
fs.Close();

Image1.ImageUrl=fileName;//将图片显示在Image控件中
g.Dispose();
bitmap.Dispose();
image.Dispose();
}