欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

winform实现为web项目上传图片的功能

程序员文章站 2023-02-28 12:55:12
项目中有个需求:用winform维护web服务器端的数据,其中需要添加图片,且图片上传需要考虑手机端,要将图片压缩后存在另个文件夹下由手机端调用,以此减轻手机端的数据量过大的负担。...
项目中有个需求:用winform维护web服务器端的数据,其中需要添加图片,且图片上传需要考虑手机端,要将图片压缩后存在另个文件夹下由手机端调用,以此减轻手机端的数据量过大的负担。

实现思路如下:1.用webservice作为winform的数据层对web服务器数据进行维护;2.webservice中添加如下代码由winform调用:

#region---上传图片---

        /// <summary>

        /// 

        /// </summary>

        /// <param name="content"></param>

        /// <param name="pathandname"></param>

        /// <returns></returns>

        [WebMethod]

        public int UpLoadFile(byte[] content, string pathandname)

        {

            int result = -2;//-2,未知错误,-1上传失败,1web图片上传成功但手机图片未成功上传,2web和手机图片都上传成功。

            try

            {

                string phonePicturePath = ConfigurationManager.AppSettings["phonePicturePath"];

                int percentage = Convert.ToInt32(ConfigurationManager.AppSettings["percentage"]);

                int index = pathandname.LastIndexOf(".");

                if (index == 0)

                {

                    result = -1;

                }

                else

                {

                    string extended = string.Empty;

                    if (index + 1 == pathandname.Length)

                    {

                        result = -1;

                    }

                    else

                    {

                        extended = pathandname.Substring(index + 1);

                        if (extended == "jpeg" || extended == "gif" || extended == "jpg" || extended == "png")

                        {

                            try

                            {

                                File.WriteAllBytes(Server.MapPath(pathandname), content);//web上传成功

                                result = 1;

                                phonePicturePath += pathandname.Substring(pathandname.LastIndexOf('/'));

                                if (GetPicThumbnail(pathandname, phonePicturePath, percentage))//全部上传成功

                                {

                                    result = 2;

                                }

                            }

                            catch (Exception ex)

                            {

                                result = -1;

                            }

 

                        }

                        else

                        {

                            result = -1;

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                result = -1;

            }

            return result;

        }

 

        /// <summary>

        /// 压缩图片

        /// </summary>

        /// <param name="sFile">文件路径</param>

        /// <param name="outPath">存放路径</param>

        /// <param name="flag">压缩比率</param>

        /// <returns>Boolean</returns>

        [WebMethod]

        public bool GetPicThumbnail(string sFile, string outPath, int flag)

        {

            System.Drawing.Image iSource = System.Drawing.Image.FromFile(Server.MapPath(sFile));

            ImageFormat tFormat = iSource.RawFormat;

 

            //以下代码为保存图片时,设置压缩质量 

            EncoderParameters ep = new EncoderParameters();

            long[] qy = new long[1];

            qy[0] = flag;//设置压缩的比例1-100 

            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);

            ep.Param[0] = eParam;

            try

            {

                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();

                ImageCodecInfo jpegICIinfo = null;

                for (int x = 0; x < arrayICI.Length; x++)

                {

                    if (arrayICI[x].FormatDescription.Equals("JPEG"))

                    {

                        jpegICIinfo = arrayICI[x];

                        break;

                    }

                }

                if (jpegICIinfo != null)

                {

                    iSource.Save(Server.MapPath(outPath), jpegICIinfo, ep);//dFile是压缩后的新路径 

                }

                else

                {

                    iSource.Save(outPath, tFormat);

                }

                return true;

            }

            catch

            {

                return false;

            }

            finally

            {

                iSource.Dispose();

                iSource.Dispose();

            }

        }

        #endregion

 

3.然后winform端代码如下:

private void btnCommonFile_Click(object sender, EventArgs e)

        {

            OpenFileDialog fileDialog = new OpenFileDialog();

            if (fileDialog.ShowDialog() == DialogResult.OK)

            {

                string extension = Path.GetExtension(fileDialog.FileName);

                string[] str = new string[] { ".gif", ".jpeg", ".jpg", "png" };

                if (!str.Contains(extension))

                {

                    MessageBox.Show("仅能上传gif,jpeg,jpg,png格式的图片!");

                }

                else

                {

                    FileInfo fileInfo = new FileInfo(fileDialog.FileName);

                    if (fileInfo.Length > (FILE_SIZE * 1024) * 1024)

                    {

                        MessageBox.Show("上传的图片不能大于5MB");

                    }

                    else

                    {

                        Stream file = fileDialog.OpenFile();

                        byte[] bytes = new byte[file.Length];

                        file.Read(bytes, 0, bytes.Length);

                        DateTime time = DateTime.Now;

                        //重命名图片的名称与路径  www.2cto.com

                        string path_name = "/images/" + time.ToString("yyyyMMddHHmmss") + extension;

                        if (tb.UploadFile(bytes, path_name, extension) != "-1")

                        {

                            MessageBox.Show("上传功能!");

                            this.txtpicture.Text = path_name;

                        }

                    }

                }

            }

        }

4.至此全部工作做完。