图片上传,包含读取图片字节大小及长宽,及Base64转换

80酷酷网    80kuku.com

  上传|转换<form id="PicAdd" method="post" runat="server" enctype="multipart/form-data">
    <input type="file" runat="server" id="Pic" NAME="Pic">
</form>
'++++++++++++++++++++++以下为读取代码
HttpPostedFile     UpFile=Pic.PostedFile;//读取数据
            FileLength=UpFile.ContentLength;//取得数据的长度
//判断是不是上传了图片
            if(FileLength==0)
            {
                Message.InnerHtml="请选择要上传的文件";
                Message.Style["color"]="red";
            }
            else
            {
                //这里判断一下字节大小
                PIC.PicClass Length=new PIC.PicClass();
                bool CheckResult=Length.CheckBytes(FileLength);
                if(CheckResult==false)
                {
                    Message.InnerHtml="图片字节数不能超过20K";
                    Message.Style["color"]="red";
                }
                else
                {
                    //判断图片的长和宽
                    Byte[] FileByteArray=new byte[FileLength];//图象文件临时存储到Byte数组里
                    Stream StreamObject=UpFile.InputStream;//建立数据流对象
                    StreamObject.Read (FileByteArray,0,FileLength);
                    //转换成Base64格式
                    PIC.PicClass ByteToBase=new PIC.PicClass();
                    string Base64String=ByteToBase.ByteToBase64(FileByteArray,0,FileByteArray.Length );
                    //建立图片对象
                    System.Drawing.Image MyImage=System.Drawing.Image.FromStream(StreamObject);
                    //开始判断图片的大小
                    PIC.PicClass CheckImage=new PIC.PicClass();
                    bool CheckImageResult=CheckImage.CheckImage(MyImage.Width ,MyImage.Height );
                    if(CheckImageResult==false)
                    {
                        Message.InnerHtml="请注意图片长宽控制在132*146之内";
                        Message.Style["color"]="red";
                    }
                    else
                    {
                        try
                        {
                           //这里省略了数据库的操作
                         }
‘++++++++++++以下为判断字节大小,图片大小,及Base64转换
public bool CheckBytes(int FileLength)
        {
            bool Result=true;
            int Length=20480;
            if(FileLength>Length)
            {
                Result=false;
            }
            return Result;
        }
        public bool CheckImage(int Width,int Height)
        {
            bool Result=true;
            int width=132,height=146;
            if(Width>width||Height>height)
            {
                Result=false;
            }
            return Result;
        }
        //这里是进行二进制到Base64的转换
        public string ByteToBase64(byte[] ByteArry,int Start,int Length)
        {
            string Result;
            Result=System.Convert.ToBase64String(ByteArry,Start,Length);
            return Result;
        }

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: