Save() public méthode

public Save ( Stream stream, ImageFormat format ) : void
stream Stream
format ImageFormat
Résultat void
        private void RegisterCommands(ImagePresentationViewModel viewModel)
        {
            viewModel.SaveCommand = UICommand.Regular(() =>
            {
                var dialog = new SaveFileDialog
                {
                    Filter = "PNG Image|*.png|Bitmap Image|*.bmp",
                    InitialDirectory = Settings.Instance.DefaultPath
                };
                var dialogResult = dialog.ShowDialog();
                if (dialogResult.HasValue && dialogResult.Value)
                {
                    var tmp = viewModel.Image;
                    using (var bmp = new Bitmap(tmp))
                    {
                        if (File.Exists(dialog.FileName))
                        {
                            File.Delete(dialog.FileName);
                        }

                        switch (dialog.FilterIndex)
                        {
                            case 0:
                                bmp.Save(dialog.FileName, ImageFormat.Png);
                                break;
                            case 1:
                                bmp.Save(dialog.FileName, ImageFormat.Bmp);
                                break;
                        }
                    }
                }
            });
        }
Exemple #2
3
 private void TakeSnapshot()
 {
     var stamp = DateTime.Now.ToString("yyyy-MM-dd-HH-mm");
     Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb);
     Graphics.FromImage(bmp).CopyFromScreen(0, 0, 0, 0, bmp.Size);
     bmp.Save(@"C:\Temp\" + stamp + ".jpg", ImageFormat.Jpeg);
 }
 /// <summary>
 /// Capture the screen and saves as image
 /// </summary>
 /// <returns> The creted image filename</returns>
 public string CaptureScreen()
 {
     date = DateTime.Now.ToString("ddMMyyyy");
     string fileName = DateTime.Now.ToString("hhmmss");
     int ix, iy, iw, ih;
     ix = Convert.ToInt32(Screen.PrimaryScreen.Bounds.X);
     iy = Convert.ToInt32(Screen.PrimaryScreen.Bounds.Y);
     iw = Convert.ToInt32(Screen.PrimaryScreen.Bounds.Width);
     ih = Convert.ToInt32(Screen.PrimaryScreen.Bounds.Height);
     Bitmap image = new Bitmap(iw, ih,
            System.Drawing.Imaging.PixelFormat.Format32bppArgb);
     Graphics g = Graphics.FromImage(image);
     g.CopyFromScreen(ix, iy, ix, iy,
              new System.Drawing.Size(iw, ih),
              CopyPixelOperation.SourceCopy);
     try
     {
         if (Directory.Exists(GlobalContants.screenshotFolderPath))
             image.Save(Path.Combine(GlobalContants.screenshotFolderPath, fileName + ".jpeg"), ImageFormat.Jpeg);
         else
         {
             Directory.CreateDirectory(GlobalContants.screenshotFolderPath);
             image.Save(Path.Combine(GlobalContants.screenshotFolderPath, fileName + ".jpeg"), ImageFormat.Jpeg);
         }
     }
     catch (Exception) { }
     return fileName;
 }
Exemple #4
0
        void iDS.Save(Bitmap b, string fileName)
        {
            var formatFile = fileName;
            formatFile = formatFile.Substring(formatFile.Length - 3);

            switch (formatFile)
            {
                case "bmp":
                    b.Save(fileName, System.Drawing.Imaging.ImageFormat.Bmp);
                    break;
                case "jepg":
                case "jpg":
                    b.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                    break;
                case "png":
                    b.Save(fileName, System.Drawing.Imaging.ImageFormat.Png);
                    break;
                case "gif":
                    b.Save(fileName, System.Drawing.Imaging.ImageFormat.Gif);
                    break;
                case "tiff":
                    b.Save(fileName, System.Drawing.Imaging.ImageFormat.Tiff);
                    break;
            }           
        }
Exemple #5
0
 private void timer1_Tick(object sender, EventArgs e)
 {
     if (Clipboard.ContainsImage() & System.IO.Directory.Exists(textBox1.Text))
     {
         frameNr++;
         Bitmap scr = new Bitmap(Clipboard.GetImage());
         if (checkBox1.Checked)
         {
             Graphics g = Graphics.FromImage(scr);
             Rectangle re = new Rectangle();
             re.X = MousePosition.X - 10;
             re.Y = MousePosition.Y - 10;
             re.Size = Cursor.Size;
             Cursor.Draw(g, re);
         }
         if (!System.IO.Directory.Exists(textBox1.Text + "\\Pictures"))
             System.IO.Directory.CreateDirectory(textBox1.Text + "\\Pictures");
         string fn = frameNr.ToString();
         while (fn.Length < 3)
             fn = "0" + fn;
         if (radioButton3.Checked)
             scr.Save(textBox1.Text + "\\Pictures\\" + fn + radioButton3.Text, System.Drawing.Imaging.ImageFormat.Bmp);
         else if (radioButton1.Checked)
             scr.Save(textBox1.Text + "\\Pictures\\" + fn + radioButton1.Text, System.Drawing.Imaging.ImageFormat.Jpeg);
         else if (radioButton2.Checked)
             scr.Save(textBox1.Text + "\\Pictures\\" + fn + radioButton2.Text, System.Drawing.Imaging.ImageFormat.Png);
         Clipboard.Clear();
         Application.DoEvents();
     }
 }
Exemple #6
0
        private void Form1_Load(object sender, EventArgs e)
        {
            Bitmap bmpImage = new Bitmap("sagarmatha.jpg");
            pictureBox1.Image = new Bitmap("sagarmatha.jpg");
            int width = bmpImage.Width;
            int height = bmpImage.Height;
            for (int j = 0; j< height; j++)
            {
                for (int i = 0; i< width; i++)
                {
                    Color pixel1 = bmpImage.GetPixel(i, j);
                    Color newcolor = Color.FromArgb(pixel1.A, pixel1.R, 0, 0);
                    bmpImage.SetPixel(i, j, newcolor);
                }

                bmpImage.Save("output_redscale.jpg");
                }
            for (int j = 0; j < height; j++)
            {
                for (int i = 0; i < width; i++)
                {
                    Color pixel1 = bmpImage.GetPixel(i, j);
                    int average = (pixel1.R + pixel1.G + pixel1.B) / 3;
                    Color newcolor = Color.FromArgb(0, average, average, average);
                    bmpImage.SetPixel(i, j, newcolor);
                }
                bmpImage.Save("output_grayscale.jpg");
                }
            pictureBox2.Image = new Bitmap("output_redscale.jpg");
            pictureBox3.Image = new Bitmap("output_grayscale.jpg");
        }
        private static void GetImageStream( ImageFormat outputFormat, Bitmap bitmap, MemoryStream ms )
        {
            var imageEncoders = ImageCodecInfo.GetImageEncoders ();
            var encoderParameters = new EncoderParameters (1);
            encoderParameters.Param[0] = new EncoderParameter (Encoder.Quality, 100L);

            if (ImageFormat.Jpeg.Equals (outputFormat))
            {
                bitmap.Save (ms, imageEncoders[1], encoderParameters);
            }
            else if (ImageFormat.Png.Equals (outputFormat))
            {
                bitmap.Save (ms, imageEncoders[4], encoderParameters);
            }
            else if (ImageFormat.Gif.Equals (outputFormat))
            {
                var quantizer = new OctreeQuantizer (255, 8);
                using (var quantized = quantizer.Quantize (bitmap))
                {
                    quantized.Save (ms, imageEncoders[2], encoderParameters);
                }
            }
            else if (ImageFormat.Bmp.Equals (outputFormat))
            {
                bitmap.Save (ms, imageEncoders[0], encoderParameters);
            }
            else
            {
                bitmap.Save (ms, outputFormat);
            }
        }
        static void Main(string[] args)
        {
            FileSize("noname.jpg");
            var image = new Bitmap("noname.jpg");

            var jgpEncoder = GetEncoder(ImageFormat.Jpeg);
            var myEncoder = Encoder.Quality;

            var myEncoderParameters = new EncoderParameters(1);
            var myEncoderParameter = new EncoderParameter(myEncoder, 50L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            image.Save(@"TestPhotoQualityFifty.jpg", jgpEncoder, myEncoderParameters);
            FileSize("TestPhotoQualityFifty.jpg");

            myEncoderParameter = new EncoderParameter(myEncoder, 100L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            image.Save(@"TestPhotoQualityHundred.jpg", jgpEncoder, myEncoderParameters);
            FileSize("TestPhotoQualityHundred.jpg");

            myEncoderParameter = new EncoderParameter(myEncoder, 70L);
            myEncoderParameters.Param[0] = myEncoderParameter;
            image.Save(@"TestPhotoQualityZero.jpg", jgpEncoder, myEncoderParameters);
            FileSize("TestPhotoQualityZero.jpg");

            Console.ReadLine();
        }
Exemple #9
0
 private void saveImage2File(Bitmap screenshot, string fileName)
 {
     if (String.IsNullOrEmpty(fileName))
         return;
     string ext = Path.GetExtension(fileName);
     switch (ext.ToLower())
     {
         case ".png":
             screenshot.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
             break;
         case ".jpg":
         case ".jpeg":
             screenshot.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
             break;
         case ".tiff":
             screenshot.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
             break;
         case ".bmp":
             screenshot.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
             break;
         case ".gif":
             screenshot.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);
             break;
     }
 }
        private static void LoadImage(HttpPostedFileBase file, string filename, string folder)
        {
            string largePhotoFullName = Path.Combine(HttpContext.Current.Server.MapPath("~/Content"),
                                                  folder, "FullSize", file.FileName);
            string smallPhotoFullName = Path.Combine(HttpContext.Current.Server.MapPath("~/Content"),
                                                    folder, "Small", file.FileName);

            if (!String.IsNullOrEmpty(file.FileName))
            {
                file.SaveAs(largePhotoFullName);
                try
                {
                    //изменяем размер изображения и перезаписываем на диск
                    var imageLogo = System.Drawing.Image.FromFile(largePhotoFullName);
                    var bitmapLogo = new Bitmap(imageLogo);
                    imageLogo.Dispose();
                    int newWidth = 500;
                    bitmapLogo = Resize(bitmapLogo, newWidth, bitmapLogo.Height * newWidth / bitmapLogo.Width);
                    bitmapLogo.Save(largePhotoFullName);
                    newWidth = 100;
                    bitmapLogo = Resize(bitmapLogo, newWidth, bitmapLogo.Height * newWidth / bitmapLogo.Width);
                    bitmapLogo.Save(smallPhotoFullName);

                    //пересохраняем с нужным нам названием
                    File.Move(largePhotoFullName, HttpContext.Current.Server.MapPath("~/Content/" + folder + "/FullSize/") + filename);
                    File.Move(smallPhotoFullName, HttpContext.Current.Server.MapPath("~/Content/" + folder + "/Small/") + filename);
                }
                catch //пользователь загрузил не изображение (ну или другая ошибка)
                {
                    File.Delete(largePhotoFullName);
                    File.Delete(smallPhotoFullName);
                }
            }
        }
Exemple #11
0
 private void button2_Click(object sender, EventArgs e)
 {
     Bitmap[] bimp = new Bitmap[openFileDialog1.SafeFileNames.Length];
     for (int i = 0; i < bimp.Length; i++)
     {
         bimp[i] = new Bitmap(openFileDialog1.FileNames[i]);
     }
     Bitmap resutl = new Bitmap(bimp[0].Width * bimp.Length, bimp[1].Height);
     Graphics q = Graphics.FromImage(resutl);
      //   q.ScaleTransform(0.5f, 0.5f);
     for (int i = 0; i < bimp.Length; i++)
     {
         q.DrawImage((Image)bimp[i], new Point(bimp[i].Width * i, 0));
     }
     q.Flush();
     if ((!checkBox1.Checked) && (saveFileDialog1.FileName != null))
     {
         resutl.Save(saveFileDialog1.FileName, System.Drawing.Imaging.ImageFormat.Png);
     }
     else
     {
         resutl.Save(openFileDialog1.FileNames[0] + "RESULT.png", System.Drawing.Imaging.ImageFormat.Png);
     }
     MessageBox.Show("Готово");
 }
Exemple #12
0
        public static void BmpSave(Bitmap newBmp, string outFile)
        {
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;

            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[x];//设置JPEG编码
                    break;
                }
            }

            if (jpegICI != null)
            {
                newBmp.Save(outFile, jpegICI, encoderParams);
            }
            else
            {
                newBmp.Save(outFile, ImageFormat.Jpeg);
            }
            newBmp.Dispose();
        }
 public Image SizeScaling(Bitmap image, int width, int height, bool distorted)
 {
     try
     {
         double realRatio = ((double) image.Height)/((double) image.Width);
         if (width != 0 & height != 0)
         {
             if (distorted) return image.GetThumbnailImage(width, height, ThumbnailCallback, IntPtr.Zero);
             var heightAfterRatio = (int) Math.Floor(realRatio*width);
             var widthAfterRatio = (int) Math.Floor(height/realRatio);
             using (var mem1 = new MemoryStream())
             {
                 using (var mem2 = new MemoryStream())
                 {
                     image.Save(mem1, ImageFormat.Tiff);
                     ImageBuilder.Current.Build(new ImageJob(mem1, mem2,
                         new ResizeSettings(widthAfterRatio, heightAfterRatio, FitMode.None, null)));
                     return Image.FromStream(mem2);
                 }
             }
             //return image.GetThumbnailImage(widthAfterRatio, heightAfterRatio, ThumbnailCallback, IntPtr.Zero);
         }
         if (width != 0)
         {
             var heightAfterRatio = (int) Math.Floor(realRatio*width);
             using (var mem1 = new MemoryStream())
             {
                 using (var mem2 = new MemoryStream())
                 {
                     image.Save(mem1, ImageFormat.Jpeg);
                     ImageBuilder.Current.Build(new ImageJob(mem1, mem2,
                         new ResizeSettings(width, heightAfterRatio, FitMode.None, null)));
                     return Image.FromStream(mem2);
                 }
             }
             //return image.GetThumbnailImage(width, heightAfterRatio, ThumbnailCallback, IntPtr.Zero);
         }
         if (height != 0)
         {
             var widthAfterRatio = (int) Math.Floor(height/realRatio);
             using (var mem1 = new MemoryStream())
             {
                 using (var mem2 = new MemoryStream())
                 {
                     image.Save(mem1, ImageFormat.Jpeg);
                     ImageBuilder.Current.Build(new ImageJob(mem1, mem2,
                         new ResizeSettings(widthAfterRatio, height, FitMode.None, null)));
                     return Image.FromStream(mem2);
                 }
             }
             //return image.GetThumbnailImage(widthAfterRatio, height, ThumbnailCallback, IntPtr.Zero);
         }
         return image;
     }
     catch (Exception ex)
     {
         return image;
     }
 }
 public static void GenThumbnail(Image imageFrom, string pathImageTo, int width, int height,string fileExt)
 {
     if (imageFrom == null)
     {
         return;
     }
     // 源图宽度及高度
     int imageFromWidth = imageFrom.Width;
     int imageFromHeight = imageFrom.Height;
     // 生成的缩略图实际宽度及高度
     int bitmapWidth = width;
     int bitmapHeight = height;
     // 生成的缩略图在上述"画布"上的位置
     int X = 0;
     int Y = 0;
     // 根据源图及欲生成的缩略图尺寸,计算缩略图的实际尺寸及其在"画布"上的位置
     if (bitmapHeight * imageFromWidth > bitmapWidth * imageFromHeight)
     {
         bitmapHeight = imageFromHeight * width / imageFromWidth;
         Y = (height - bitmapHeight) / 2;
     }
     else
     {
         bitmapWidth = imageFromWidth * height / imageFromHeight;
         X = (width - bitmapWidth) / 2;
     }
     // 创建画布
     Bitmap bmp = new Bitmap(width, height);
     Graphics g = Graphics.FromImage(bmp);
     // 用白色清空
     g.Clear(Color.White);
     // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。
     g.InterpolationMode = InterpolationMode.HighQualityBicubic;
     // 指定高质量、低速度呈现。
     g.SmoothingMode = SmoothingMode.HighQuality;
     // 在指定位置并且按指定大小绘制指定的 Image 的指定部分。
     g.DrawImage(imageFrom, new Rectangle(X, Y, bitmapWidth, bitmapHeight), new Rectangle(0, 0, imageFromWidth, imageFromHeight), GraphicsUnit.Pixel);
     try
     {
         //经测试 .jpg 格式缩略图大小与质量等最优
         if (fileExt == ".png")
         {
             bmp.Save(pathImageTo, ImageFormat.Png);
         }
         else
         {
             bmp.Save(pathImageTo, ImageFormat.Jpeg);
         }
     }
     catch
     {
     }
     finally
     {
         //显示释放资源
         bmp.Dispose();
         g.Dispose();
     }
 }
Exemple #15
0
        /// <summary>
        /// 生成验证码图片
        /// </summary>
        private void CreateVerifyImg()
        {
            string vMapPath = string.Empty;                     //验证码路径
            Random rnd = new Random();                          //随机发生器
            Bitmap imgTemp = null;                              //验证码图片
            Graphics g = null;                                  //图形库函数
            SolidBrush blueBrush = null;                        //缓冲区

            //暂时注销
            //string rndstr = rnd.Next(1111, 9999).ToString();    //验证码

            string rndstr = string.Empty;    //验证码
            //测试时,将验证码统一设为0000
            rndstr = rnd.Next(1111, 9999).ToString();

            int totalwidth = 0;                                 //验证码图片总宽度
            int totalheight = 0;                                //验证码图片总高度

            //给缓存添加验证码
            SetVerifyCookie(rndstr);

            //生成验证码图片文件
            System.Drawing.Image ReducedImage1 = System.Drawing.Image.FromFile(Server.MapPath("images/yzm/" + rndstr.Substring(0, 1) + ".gif"));
            System.Drawing.Image ReducedImage2 = System.Drawing.Image.FromFile(Server.MapPath("images/yzm/" + rndstr.Substring(1, 1) + ".gif"));
            System.Drawing.Image ReducedImage3 = System.Drawing.Image.FromFile(Server.MapPath("images/yzm/" + rndstr.Substring(2, 1) + ".gif"));
            System.Drawing.Image ReducedImage4 = System.Drawing.Image.FromFile(Server.MapPath("images/yzm/" + rndstr.Substring(3, 1) + ".gif"));

            totalwidth = 52;
            totalheight = 17;
            imgTemp = new Bitmap(totalwidth, totalheight);
            g = Graphics.FromImage(imgTemp);
            blueBrush = new SolidBrush(Color.Black);
            g.FillRectangle(blueBrush, 0, 0, totalwidth, totalheight);
            g.DrawImage(ReducedImage1, 0, 0);
            g.DrawImage(ReducedImage2, ReducedImage1.Width, 0);
            g.DrawImage(ReducedImage3, ReducedImage1.Width + ReducedImage2.Width, 0);
            g.DrawImage(ReducedImage4, ReducedImage1.Width + ReducedImage2.Width + ReducedImage3.Width, 0);

            vMapPath = Server.MapPath("images/yzm/verify.gif");
            try
            {
                imgTemp.Save(vMapPath);
            }
            catch
            {
                //utils.JsAlert("创建验证验错误!");
            }

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            imgTemp.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());

            blueBrush.Dispose();
            g.Dispose();
            imgTemp.Dispose();
        }
Exemple #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            // Displays a SaveFileDialog so the user can save the Image
            // assigned to Button2.
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();
            saveFileDialog1.Filter = "Png Image|*.png|Bitmap Image|*.bmp|Gif Image|*.gif";
            saveFileDialog1.Title = "Save an Image File";
            saveFileDialog1.ShowDialog();
            Random gen = new Random();
            SudokuTabla sud;

            Image img= new Bitmap(1020+20,520*(listBox1.SelectedIndex+1)/2);
            Graphics g = Graphics.FromImage(img);
                g.Clear(Color.White);
                g.TextRenderingHint = TextRenderingHint.AntiAlias;
                g.TextContrast = 8;
            List<Image> lista = new List<Image>();
            for (int i = 0; i < listBox1.SelectedIndex + 1; i++) {
                 sud = new SudokuTabla(gen);
                sud.polni();
                sud.prazni();
                Image im= new Bitmap(500, 500);
                SimpleSudoku.draw(sud, im, Color.Black, true);
                g.DrawImageUnscaled(im, 500 * (i % 2)+20, 500 * (i / 2)+20);

            }

                // If the file name is not an empty string open it for saving.
                if (saveFileDialog1.FileName != "")
                {
                    // Saves the Image via a FileStream created by the OpenFile method.
                    System.IO.FileStream fs =
                       (System.IO.FileStream)saveFileDialog1.OpenFile();
                    // Saves the Image in the appropriate ImageFormat based upon the
                    // File type selected in the dialog box.
                    // NOTE that the FilterIndex property is one-based.
                    switch (saveFileDialog1.FilterIndex)
                    {
                        case 1:
                            img.Save(fs,
                             System.Drawing.Imaging.ImageFormat.Png);
                            break;

                        case 2:
                            img.Save(fs,
                               System.Drawing.Imaging.ImageFormat.Bmp);
                            break;

                        case 3:
                            img.Save(fs,
                               System.Drawing.Imaging.ImageFormat.Gif);
                            break;
                    }

                    fs.Close();
                }
        }
        // Copied from http://stackoverflow.com/questions/27921/what-is-the-best-way-to-create-a-thumbnail-using-asp-net

        public static void ResizeImage(string fileNameInput, string fileNameOutput, double resizeHeight, double resizeWidth, ImageFormat outputFormat)
        {
            using (System.Drawing.Image photo = new Bitmap(fileNameInput))
            {
                double aspectRatio = (double)photo.Width / photo.Height;
                double boxRatio = resizeWidth / resizeHeight;
                double scaleFactor = 0;

                if (photo.Width < resizeWidth && photo.Height < resizeHeight)
                {
                    // Keep the image the same size since it is already smaller than our max width/height
                    scaleFactor = 1.0;
                }
                else
                {
                    // Compare the ratios to determine if the picture should be resized by height or width.
                    if (boxRatio > aspectRatio)
                        scaleFactor = resizeHeight / photo.Height;
                    else
                        scaleFactor = resizeWidth / photo.Width;
                }

                int newWidth = (int)(photo.Width * scaleFactor);
                int newHeight = (int)(photo.Height * scaleFactor);

                using (Bitmap bmp = new Bitmap(newWidth, newHeight))
                {
                    using (Graphics g = Graphics.FromImage(bmp))
                    {
                        g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        g.SmoothingMode = SmoothingMode.HighQuality;
                        g.CompositingQuality = CompositingQuality.HighQuality;
                        g.PixelOffsetMode = PixelOffsetMode.HighQuality;

                        g.DrawImage(photo, 0, 0, newWidth, newHeight);

                        if (ImageFormat.Png.Equals(outputFormat))
                        {
                            bmp.Save(fileNameOutput, outputFormat);
                        }
                        else if (ImageFormat.Jpeg.Equals(outputFormat))
                        {
                            ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders();
                            EncoderParameters encoderParameters;
                            using (encoderParameters = new System.Drawing.Imaging.EncoderParameters(1))
                            {
                                // use jpeg info[1] and set quality to 90
                                encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
                                bmp.Save(fileNameOutput, info[1], encoderParameters);
                            }
                        }
                    }
                }
            }
        }
 public void CreateNewImage(string fileSaveName, int width, int height)
 {
     Bitmap bmpOut = new Bitmap(width, height);
     Graphics g = Graphics.FromImage(bmpOut);
     g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
     g.FillRectangle(Brushes.White, 0, 0, width, height);
     g.DrawImage(new Bitmap(this.Images.InputStream), 0, 0, width, height);
     MemoryStream stream = new MemoryStream();
     bmpOut.Save(stream, ImageFormat.Jpeg);
     bmpOut.Save(fileSaveName);
 }
Exemple #19
0
        public ActionResult AddArticle( Article article, HttpPostedFileBase picture, int categoryId )
        {
            if( ModelState.IsValid )
            {

                if( picture != null )
                {
                    if( picture.ContentType == "image/jpeg" || picture.ContentType == "image/png" )
                    {
                        Image image = Image.FromStream( picture.InputStream );

                        if( image.Height > 200 || image.Width > 200 )
                        {
                            Image small = Class.ImageHelper.ScaleImage( image, 200, 200 );
                            Bitmap b = new Bitmap( small );

                            Guid guid = Guid.NewGuid();
                            string imageName = guid.ToString() + ".jpg";

                            b.Save( Server.MapPath( "~/uploads/aticleImage/" + imageName ), ImageFormat.Jpeg );
                            b.Save( Server.MapPath( "~/uploads/articleImage/" + imageName ), ImageFormat.Jpeg );

                            small.Dispose();
                            b.Dispose();

                            article.ImageName = imageName;
                        }
                        else
                        {
                            picture.SaveAs( Server.MapPath( "~/uploads/Article/" + picture.FileName ) );
                        }
                    }
                }
                ArticleCategoryDao articleCategoryDao = new ArticleCategoryDao();

                ArticleCategory articleCategory = articleCategoryDao.GetById( categoryId );
                article.Category = articleCategory;
                article.PostDate = DateTime.Now;
                article.User = new BlogUserDao().GetByLogin(User.Identity.Name);
                ArticleDao articleDao = new ArticleDao();

                articleDao.Create( article );

                TempData["message-success"] = "Kniha byla pridana";

            }
            else
            {
                return View( "Create", article );
            }

            return RedirectToAction( "Index" );
        }
Exemple #20
0
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="pathpic">图片数据流</param>
        /// <param name="newspath">存储路径</param>
        /// <param name="newsname">新图片名</param>
        /// <param name="maxwidth">最大宽度</param>
        /// <param name="maxheight">最大高度</param>
        public static void SmallImage(Stream pathpic, string newspath, string newsname, int maxwidth, int maxheight)
        {
            if (!Directory.Exists(newspath))
            {
                Directory.CreateDirectory(newspath);
            }
            System.Drawing.Image img = System.Drawing.Image.FromStream(pathpic);
            System.Drawing.Imaging.ImageFormat thisFormat = img.RawFormat;

            Size newSize = NewSize(maxwidth, maxheight, img.Width, img.Height);
            Bitmap outBmp = new Bitmap(newSize.Width, newSize.Height);
            Graphics g = Graphics.FromImage(outBmp);

            // 设置画布的描绘质量
            g.CompositingQuality = CompositingQuality.HighQuality;
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;

            g.DrawImage(img, new Rectangle(0, 0, newSize.Width, newSize.Height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
            g.Dispose();

            // 以下代码为保存图片时,设置压缩质量
            EncoderParameters encoderParams = new EncoderParameters();
            long[] quality = new long[1];
            quality[0] = 100;

            EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
            encoderParams.Param[0] = encoderParam;

            //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。
            ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo jpegICI = null;
            for (int x = 0; x < arrayICI.Length; x++)
            {
                if (arrayICI[x].FormatDescription.Equals("JPEG"))
                {
                    jpegICI = arrayICI[x];//设置JPEG编码
                    break;
                }
            }

            if (jpegICI != null)
            {
                outBmp.Save(newspath + newsname, jpegICI, encoderParams);

            }
            else
            {
                outBmp.Save(newspath + newsname, thisFormat);
            }
            img.Dispose();
            outBmp.Dispose();
        }
 public override IGAnswer CreateAnswer()
 {
     IGSMAnswer.IGSMANSWER_ERROR_CODE nErrorCode = IGSMAnswer.IGSMANSWER_ERROR_CODE.IGSMANSWER_ERROR_REQUESTPROCESSING;
     string firstImageName = "";
     try
     {
         string sLogin = GetAttributeValue(IGREQUEST_USERLOGIN);
         foreach (string sImageInputPath in m_lsInputPath)
         {
             if ((Path.GetExtension(sImageInputPath).ToUpper() != ".JPG") &&
                 (Path.GetExtension(sImageInputPath).ToUpper() != ".PNG") &&
                 (Path.GetExtension(sImageInputPath).ToUpper() != ".BMP"))
             {
                 nErrorCode = IGSMAnswer.IGSMANSWER_ERROR_CODE.IGSMANSWER_ERROR_WRONGFILEFORMAT;
                 throw new FormatException();
             }
             else if (sImageInputPath.Contains(","))
             {
                 nErrorCode = IGSMAnswer.IGSMANSWER_ERROR_CODE.IGSMANSWER_ERROR_INVALIDFILENAME;
                 throw new FormatException();
             }
             string sImageName = sImageInputPath.Substring(sImageInputPath.IndexOf('$') + 1);
             string sImageNameJPEG = sImageName.Remove(sImageName.Length - Path.GetExtension(sImageName).Length) + "$" + GetAttributeValue(IGREQUEST_GUID) + ".JPG";
             Image imgInput = Image.FromFile(sImageInputPath);
             float fRate = HC.MINIPICTURE_MAXSIZE / (float)Math.Max(imgInput.Size.Width, imgInput.Size.Height);
             Image imgMini = new Bitmap(imgInput, new Size((int)((float)imgInput.Size.Width * fRate), (int)((float)imgInput.Size.Height * fRate)));
             imgMini.Save(HC.PATH_USERACCOUNT + sLogin + HC.PATH_USERMINI + HC.PATH_PREFIXMINI + sImageName, ImageFormat.Jpeg);
             imgMini.Save(HC.PATH_OUTPUT + sLogin + HC.PATH_OUTPUTMINI + HC.PATH_PREFIXMINI + sImageNameJPEG, ImageFormat.Jpeg);
             string sDestPath = HC.PATH_USERACCOUNT + sLogin + HC.PATH_USERIMAGES + sImageName;
             if (firstImageName == "")
                 firstImageName = sImageName;
             m_lsImageSize.Add(new KeyValuePair<int, int>(imgMini.Width, imgMini.Height));
             if (File.Exists(sDestPath))
             {
                 nErrorCode = IGSMAnswer.IGSMANSWER_ERROR_CODE.IGSMANSWER_ERROR_FILEALREADYEXISTS;
                 throw new IOException();
             }
             File.Copy(sImageInputPath, sDestPath);
         }
         m_timerDeletor.Start();
     }
     catch (Exception exc)
     {
         IGServerManager.Instance.AppendError(exc.ToString());
         m_timerDeletor.Start();
         if (nErrorCode != IGSMAnswer.IGSMANSWER_ERROR_CODE.IGSMANSWER_ERROR_FILEALREADYEXISTS)
             return new IGSMAnswerError(this, nErrorCode);
     }
     SetParameter(IGAnswer.IGANSWER_SERVERIP, m_serverMgr.ServerIP.ToString());
     SetParameter(IGSMREQUEST_PARAM_LISTSIZE, createParamFromList(m_lsImageSize));
     return new IGSMAnswerUploadSucceeded(this, firstImageName);
 }
Exemple #22
0
        static void Main(string[] args)
        {
            Bitmap source = new Bitmap("bitmap.png");
            char[] ascii = " !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~".ToCharArray();
            bool useAscii;
            int h_div, v_div;

            Console.WriteLine("I can use ascii encoding? (Y/N)");
            if (Console.ReadKey(false).Key == ConsoleKey.Y)
                useAscii = true;
            else
                useAscii = false;
            Console.WriteLine("\nKthx");

            Console.WriteLine("I can haz teh horizontal dividr: ");
            while(true)
            {
                if (Int32.TryParse(Console.ReadLine().ToString(), out h_div))
                    break;
                else
                    Console.WriteLine("Teh input iz not numerical");
            }
            Console.WriteLine("Kthx");

            Console.WriteLine("I can haz teh vertical dividr: ");
            while (true)
            {
                if (Int32.TryParse(Console.ReadLine().ToString(), out v_div))
                    break;
                else
                    Console.WriteLine("Teh input iz not numerical");
            }
            Console.WriteLine("Kthx");

            int numcols = (int)Math.Ceiling((double)source.Width / h_div);
            int numrows = (int)Math.Ceiling((double)source.Height / v_div);
            int numblocks = numcols*numrows;

            for (int i=0; i<numblocks; i++)
            {
                Bitmap cbitmap = new Bitmap(h_div, v_div);
                using (Graphics g = Graphics.FromImage(cbitmap))
                {
                    g.DrawImage(source, new Rectangle(0, 0, cbitmap.Width, cbitmap.Height), new Rectangle(cbitmap.Width * (i % numcols), cbitmap.Height * (int)Math.Floor((double)i/numcols), cbitmap.Width, cbitmap.Height), GraphicsUnit.Pixel);
                }
                if (useAscii && i <= ascii.Length)
                    cbitmap.Save((int)ascii[i] + ".bmp");
                else
                    cbitmap.Save(i + ".bmp");
            }
            Console.WriteLine("I is done, kthxbai");
        }
Exemple #23
0
        public ActionResult Addbook(Book book, HttpPostedFileBase picture, int categoryId)
        {
            if ( ModelState.IsValid )
            {

                if ( picture != null )
                {
                    if ( picture.ContentType == "image/jpeg" || picture.ContentType == "image/png" )
                    {
                        Image image = Image.FromStream(picture.InputStream);

                        if ( image.Height > 200 || image.Width > 200 )
                        {
                            Image small = Helper.ImageHelper.ScaleImage(image, 200, 200);
                            Bitmap b = new Bitmap(small);

                            Guid guid = Guid.NewGuid();
                            string imageName = guid.ToString() + ".jpg";

                            b.Save(Server.MapPath("~/uploads/aticleImage/" + imageName), ImageFormat.Jpeg);
                            b.Save(Server.MapPath("~/uploads/articleImage/" + imageName), ImageFormat.Jpeg);

                            small.Dispose();
                            b.Dispose();

                            book.ImageName = imageName;
                        }
                        else
                        {
                            picture.SaveAs(Server.MapPath("~/uploads/Article/" + picture.FileName));
                        }
                    }
                }
                BookCategoryDao bookCategoryDao = new BookCategoryDao();

                BookCategory bookCategory = bookCategoryDao.GetById(categoryId);
                book.Category = bookCategory;
                book.PosteDate = DateTime.Now;
                BookDao bookDao = new BookDao();

                bookDao.Create(book);

                TempData["message-success"] = "Článek byl přidán";

            }
            else
            {
                return View("Create", book);
            }

            return RedirectToAction("Index");
        }
Exemple #24
0
        /// <summary>
        /// GenerateIconFile()
        /// Generate Multiple size of Icon file from the Icone object specified in the constructor.
        /// </summary>
        /// <returns>true/false</returns>
        public Boolean GenerateIconFile()
        {
            if (this.Project.Icone == null) this.Project.Icone = Properties.Resources.Icon;

            if (this.Project.BuildFolderPath.Equals("")) return false;

            try
            {
                //Get Original Icone File
                Image Icone = new Bitmap(this.Project.Icone);

                //Resize to the Correct Size
                Bitmap Icon57x57 = new Bitmap(Icone, 57, 57);
                Bitmap Icon36x36 = new Bitmap(Icone, 36, 36);
                Bitmap Icon48x48 = new Bitmap(Icone, 48, 48);
                Bitmap Icon72x72 = new Bitmap(Icone, 72, 72);
                Bitmap Icon114x114 = new Bitmap(Icone, 114, 114);
                Bitmap Icon512x512 = new Bitmap(Icone, 512, 512);
                //Save File

                //Iphone Icone File
                Icon57x57.Save(this.Project.BuildFolderPath + "\\Icon.png", System.Drawing.Imaging.ImageFormat.Png);
                Icon72x72.Save(this.Project.BuildFolderPath + "\\Icon-72.png", System.Drawing.Imaging.ImageFormat.Png);
                Icon114x114.Save(this.Project.BuildFolderPath + "\\[email protected]", System.Drawing.Imaging.ImageFormat.Png);

                // Itune Store and Android Store Iphone
                Icon512x512.Save(this.Project.BuildFolderPath + "\\IconItunes.png", System.Drawing.Imaging.ImageFormat.Png);

                //Android Icone File
                Icon36x36.Save(this.Project.BuildFolderPath + "\\Icon-ldpi.png", System.Drawing.Imaging.ImageFormat.Png);
                Icon48x48.Save(this.Project.BuildFolderPath + "\\Icon-mdpi.png", System.Drawing.Imaging.ImageFormat.Png);
                Icon72x72.Save(this.Project.BuildFolderPath + "\\Icon-hdpi.png", System.Drawing.Imaging.ImageFormat.Png);

                Icon57x57.Dispose();
                Icon36x36.Dispose();
                Icon48x48.Dispose();
                Icon72x72.Dispose();
                Icon114x114.Dispose();
                Icon512x512.Dispose();

                Icone.Dispose();

                return true;
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error during image resizing ! \n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
        }
Exemple #25
0
 /// <summary>
 /// 图片格式转换
 /// </summary>
 /// <param name="sourcePath"></param>
 /// <param name="distationPath"></param>
 /// <param name="format"></param>
 public static void ImageFormatter(string sourcePath, string distationPath, string format)
 {
     System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(sourcePath);
     switch (format.ToLower())
     {
         case "bmp":
             bitmap.Save(distationPath, System.Drawing.Imaging.ImageFormat.Bmp);
             break;
         case "emf":
             bitmap.Save(distationPath, System.Drawing.Imaging.ImageFormat.Emf);
             break;
         case "gif":
             bitmap.Save(distationPath, System.Drawing.Imaging.ImageFormat.Gif);
             break;
         case "ico":
             bitmap.Save(distationPath, System.Drawing.Imaging.ImageFormat.Icon);
             break;
         case "jpg":
             bitmap.Save(distationPath, System.Drawing.Imaging.ImageFormat.Jpeg);
             bitmap.Dispose();
             break;
         case "png":
             bitmap.Save(distationPath, System.Drawing.Imaging.ImageFormat.Png);
             break;
         case "tif":
             bitmap.Save(distationPath, System.Drawing.Imaging.ImageFormat.Tiff);
             break;
         case "wmf":
             bitmap.Save(distationPath, System.Drawing.Imaging.ImageFormat.Wmf);
             break;
         default: throw new Exception("无法转换此格式!");
     }
 }
Exemple #26
0
    /// <summary>
    /// Read single image frame.
    /// </summary>
    /// <param name="bitmap">The bitmap to read the image from.</param>
    /// <exception cref="MagickException">Thrown when an error is raised by ImageMagick.</exception>
    public void Read(Bitmap bitmap)
    {
      Throw.IfNull(nameof(bitmap), bitmap);

      using (MemoryStream memStream = new MemoryStream())
      {
        if (IsSupportedImageFormat(bitmap.RawFormat))
          bitmap.Save(memStream, bitmap.RawFormat);
        else
          bitmap.Save(memStream, ImageFormat.Bmp);

        memStream.Position = 0;
        Read(memStream);
      }
    }
        //This code has been referenced from http://www.codeproject.com/Articles/30322/Barcodes-in-ASP-NET-applications
        protected void Page_Load(object sender, EventArgs e)
        {
            // Get the Requested code to be created.
            string Code = Request.QueryString["code"];

            if (Code != null)
            {

                // Multiply the lenght of the code by 40 (just to have enough width)
                int w = Code.Length * 40;

                // Create a bitmap object of the width that we calculated and height of 100
                Bitmap oBitmap = new Bitmap(w, 100);

                // then create a Graphic object for the bitmap we just created.
                Graphics oGraphics = Graphics.FromImage(oBitmap);

                // Now create a Font object for the Barcode Font
                // (in this case the IDAutomationHC39M) of 18 point size
                Font oFont = new Font("IDAutomationHC39M Free Version", 18);

                // Let's create the Point and Brushes for the barcode
                PointF oPoint = new PointF(2f, 2f);
                SolidBrush oBrushWrite = new SolidBrush(Color.Black);
                SolidBrush oBrush = new SolidBrush(Color.White);

                // Now lets create the actual barcode image
                // with a rectangle filled with white color
                oGraphics.FillRectangle(oBrush, 0, 0, w, 100);

                // We have to put prefix and sufix of an asterisk (*),
                // in order to be a valid barcode
                oGraphics.DrawString(Code, oFont, oBrushWrite, oPoint);

                // Then we send the Graphics with the actual barcode
                Response.ContentType = "image/jpeg";
                oBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);

                using (MemoryStream ms = new MemoryStream())
                {
                    oBitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);

                    Response.BinaryWrite(ms.ToArray());
                }
                oBitmap.Dispose();
                Response.End();
            }
        }
Exemple #28
0
 public byte[] Bitmap2JpegArray(Bitmap Frame)
 {
     MemoryStream ms = new MemoryStream();
     Frame.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
     byte[] toReturn = ms.ToArray();
     return toReturn;
 }
Exemple #29
0
        // Draw the carpet.
        private void DrawGasket()
        {
            Level = int.Parse(txtLevel.Text);

            Bitmap bm = new Bitmap(
                picGasket.ClientSize.Width,
                picGasket.ClientSize.Height);
            using (Graphics gr = Graphics.FromImage(bm))
            {
                gr.Clear(Color.White);
                gr.SmoothingMode = SmoothingMode.AntiAlias;

                // Draw the top-level carpet.
                const float margin = 10;
                RectangleF rect = new RectangleF(
                    margin, margin,
                    picGasket.ClientSize.Width - 2 * margin,
                    picGasket.ClientSize.Height - 2 * margin);
                DrawRectangle(gr, Level, rect);
            }

            // Display the result.
            picGasket.Image = bm;

            // Save the bitmap into a file.
            bm.Save("Carpet " + Level + ".bmp");
        }
Exemple #30
0
        public FileContentResult CreateImageCode()
        {
            string code = CreateVerifyCode(4);

            Session["checkcode"] = code.ToUpper();
            int fSize       = FontSize;
            int fWidth      = fSize + Padding;
            int imageWidth  = (int)(code.Length * fWidth) + 4 + Padding * 2;
            int imageHeight = 22;//fSize * 2 + Padding;

            System.Drawing.Bitmap image = new System.Drawing.Bitmap(imageWidth, imageHeight);
            Graphics g = Graphics.FromImage(image);

            g.Clear(BackgroundColor);
            Random rand = new Random();

            //给背景添加随机生成的燥点
            if (this.Chaos)
            {
                Pen pen = new Pen(ChaosColor, 0);
                int c   = Length * 10;

                for (int i = 0; i < c; i++)
                {
                    int x = rand.Next(image.Width);
                    int y = rand.Next(image.Height);

                    g.DrawRectangle(pen, x, y, 1, 1);
                }
            }

            int left = 0, top = 0, top1 = 1, top2 = 1;

            int n1 = (imageHeight - FontSize - Padding * 2);
            int n2 = n1 / 4;

            top1 = n2;
            top2 = n2 * 2;

            Font  f;
            Brush b;
            int   cindex, findex;

            //随机字体和颜色的验证码字符
            for (int i = 0; i < code.Length; i++)
            {
                cindex = rand.Next(Colors.Length - 1);
                findex = rand.Next(Fonts.Length - 1);

                f = new System.Drawing.Font(Fonts[findex], fSize, System.Drawing.FontStyle.Bold);
                b = new System.Drawing.SolidBrush(Colors[cindex]);

                if (i % 2 == 1)
                {
                    top = top2;
                }
                else
                {
                    top = top1;
                }

                left = i * fWidth;

                g.DrawString(code.Substring(i, 1), f, b, left, top);
            }

            //画一个边框 边框颜色为Color.Gainsboro
            g.DrawRectangle(new Pen(Color.Gainsboro, 0), 0, 0, image.Width - 1, image.Height - 1);
            g.Dispose();

            //产生波形
            image = TwistImage(image, true, 0, 4);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            //将图像保存到指定的流
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            return(File(ms.GetBuffer(), "image/JPEG"));
        }
Exemple #31
0
    /// <summary>
    /// 生成缩略图开始
    /// </summary>
    /// <param name="originalImagePath">源图路径(物理路径)</param>
    /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    //修改后的代码 支持动态控件传递多个 
    public static void CreateXimg(string originalImagePath, string thumbnailPath, int width, int height, string mode)
    {
        Graphics draw    = null;
        string   FileExt = "";

        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(HttpContext.Current.Server.MapPath(originalImagePath));

        int towidth  = width;
        int toheight = height;
        int x        = 0;
        int y        = 0;
        int ow       = originalImage.Width;
        int oh       = originalImage.Height;

        switch (mode)
        {
        case "HW":        //指定高宽缩放(可能变形)
            break;

        case "W":        //指定宽,高按比例
            toheight = originalImage.Height * width / originalImage.Width;
            break;

        case "H":        //指定高,宽按比例
            towidth = originalImage.Width * height / originalImage.Height;
            break;

        case "Cut":        //指定高宽裁减(不变形)
            if ((double)towidth / (double)toheight < (double)width / (double)width / (double)height)
            {
                ow = originalImage.Width;
                oh = originalImage.Width * height / towidth;
                x  = 0;
                y  = (originalImage.Height - oh) / 2;
            }
            else
            {
                oh = originalImage.Height;
                ow = originalImage.Height * towidth / toheight;
                y  = 0;
                x  = (originalImage.Width - ow) / 2;
            }
            break;

        default:
            break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap  = new System.Drawing.Bitmap(towidth, toheight);
        System.Drawing.Image bitmap2 = new System.Drawing.Bitmap(towidth, toheight);
        //新建一个画板
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);


        //设置高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //设置高质量
        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

        //清空画布并以透明背景色填充
        g.Clear(System.Drawing.Color.Transparent);

        //在指定位置并且按指定大小绘制原图片的指定部分
        g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight));

        try
        {
            //以jpg格式保存缩略图
            FileExt = Path.GetFileNameWithoutExtension(originalImagePath);
            //用新建立的image对象拷贝bitmap对象 让g对象可以释放资源
            draw = Graphics.FromImage(bitmap2);
            draw.DrawImage(bitmap, 0, 0);
        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
            //保存调整在这里即可
            bitmap2.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
Exemple #32
0
        /// <summary>
        /// 图片压缩处理
        /// </summary>
        /// <param name="ImgUrl">图片路径</param>
        /// <param name="intThumbWidth">压缩图片宽度</param>
        /// <param name="intThumbHeight">压缩图片高度</param>
        /// <param name="sThumbExtension">压缩前缀</param>
        /// <param name="sSavePath">压缩路径</param>
        /// <param name="FileName">压缩图片名称</param>
        /// <returns></returns>
        public static string SetYsImgUrl(string ImgUrl, int intThumbWidth, int intThumbHeight, string sThumbExtension, string sSavePath, string FileName)
        {
            string smallImagePath = "";

            try
            {
                //int intThumbWidth = 640;
                //int intThumbHeight = 480;
                //string sThumbExtension = "";
                //string sSavePath = "/UpLoad2/owner/";
                //原图加载
                using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(System.Web.HttpContext.Current.Server.MapPath(ImgUrl)))
                {
                    //原图宽度和高度
                    int width  = sourceImage.Width;
                    int height = sourceImage.Height;
                    int smallWidth;
                    int smallHeight;
                    //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽  和 原图的高/缩略图的高)
                    if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight)
                    {
                        smallWidth  = intThumbWidth;
                        smallHeight = intThumbWidth * height / width;
                    }
                    else
                    {
                        smallWidth  = intThumbHeight * width / height;
                        smallHeight = intThumbHeight;
                    }
                    //判断缩略图在当前文件夹下是否同名称文件存在
                    int    file_append = 0;
                    string sThumbFile  = sThumbExtension + FileName;
                    while (System.IO.File.Exists(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sThumbFile)))
                    {
                        file_append++;
                        sThumbFile = sThumbExtension + System.IO.Path.GetFileNameWithoutExtension(FileName) +
                                     file_append.ToString() + System.IO.Path.GetExtension(FileName);
                    }
                    //缩略图保存的绝对路径
                    smallImagePath = System.Web.HttpContext.Current.Server.MapPath(sSavePath) + sThumbFile;
                    //新建一个图板,以最小等比例压缩大小绘制原图
                    using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))
                    {
                        //绘制中间图
                        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                        {
                            //高清,平滑
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                            g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.Clear(Color.Black);
                            g.DrawImage(
                                sourceImage,
                                new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),
                                new System.Drawing.Rectangle(0, 0, width, height),
                                System.Drawing.GraphicsUnit.Pixel
                                );
                        }
                        //新建一个图板,以缩略图大小绘制中间图
                        using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
                        {
                            //绘制缩略图
                            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))
                            {
                                //高清,平滑
                                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                g.Clear(Color.Black);
                                int lwidth  = (smallWidth - intThumbWidth) / 2;
                                int bheight = (smallHeight - intThumbHeight) / 2;
                                g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);
                                g.Dispose();
                                bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                        }
                    }
                    smallImagePath = sSavePath + sThumbFile;
                }
            }
            catch
            {
                ////出错则删除
                //System.IO.File.Delete(System.Web.HttpContext.Current.Server.MapPath(sSavePath + sFilename));
                return("No3");
            }

            return(smallImagePath);
        }
        /// <summary>
        /// 生成缩略图 create by kouzp 2014-02-13
        /// </summary>
        /// <param name="imagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图保存路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param>
        public static void MakeThumbnail(string imagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image image = System.Drawing.Image.FromFile(imagePath);

            int towidth  = width;
            int toheight = height;

            int x  = 0;
            int y  = 0;
            int ow = image.Width;
            int oh = image.Height;

            switch (mode)
            {
            case "HW":    //指定高宽缩放(可能变形)
                break;

            case "W":    //指定宽,高按比例
                toheight = image.Height * width / image.Width;
                break;

            case "H":    //指定高,宽按比例
                towidth = image.Width * height / image.Height;
                break;

            case "Cut":    //指定高宽裁减(不变形)
                if ((double)image.Width / (double)image.Height > (double)towidth / (double)toheight)
                {
                    oh = image.Height;
                    ow = image.Height * towidth / toheight;
                    y  = 0;
                    x  = (image.Width - ow) / 2;
                }
                else
                {
                    ow = image.Width;
                    oh = image.Width * height / towidth;
                    x  = 0;
                    y  = (image.Height - oh) / 2;
                }
                break;

            default:
                break;
            }
            if (image.Width <= width && image.Height <= height)//保持原样
            {
                towidth  = image.Width;
                toheight = image.Height;
            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(image, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);

            try
            {
                int len = thumbnailPath.LastIndexOf('/');
                if (len <= 0)
                {
                    len = thumbnailPath.LastIndexOf('\\');
                }
                string        dirPath = thumbnailPath.Substring(0, len);
                DirectoryInfo dir     = new DirectoryInfo(dirPath);
                if (!dir.Exists)
                {
                    dir.Create();
                }
                //以jpg格式保存缩略图
                bitmap.Save(thumbnailPath);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                image.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
    //图片上传
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        ClearMethod();
        HttpPostedFile hpf = uploadImage.PostedFile;

        //取得文件名,不含路径
        char[]   splitChar     = { '\\' };
        string[] FilenameArray = hpf.FileName.Split(splitChar);
        string   Filename      = FilenameArray[FilenameArray.Length - 1].ToLower();

        //将用户输入的水印文字处理
        //string sMessage = lineStr(TextBox3.Text.Trim().ToString(), 20);

        if (hpf.FileName.Length < 1)
        {
            panelAttention.Visible = true;
            lbAttention.Text       = "请选择你要上传的图片文件";
            return;
        }
        if (hpf.ContentType != "image/jpeg" && hpf.ContentType != "image/gif")
        {
            panelAttention.Visible = true;
            lbAttention.Text       = "只允许上传JPEG GIF文件";
            return;
        }
        else
        {
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.Append(DateTime.Now.Year.ToString());
            sb.Append(DateTime.Now.Month.ToString());
            sb.Append(DateTime.Now.Day.ToString());
            sb.Append(DateTime.Now.Hour.ToString());
            sb.Append(DateTime.Now.Minute.ToString());
            sb.Append(DateTime.Now.Second.ToString());

            if (Filename.ToLower().EndsWith("gif"))
            {
                sb.Append(".gif");
            }
            else if (Filename.ToLower().EndsWith("jpg"))
            {
                sb.Append(".jpg");
            }
            else if (Filename.ToLower().EndsWith("jpeg"))
            {
                sb.Append(".jpeg");
            }
            Filename = sb.ToString();

            //保存图片到服务器上
            try
            {
                hpf.SaveAs(Server.MapPath("~") + "/images/onsale/wear/big_" + Filename);
            }
            catch (Exception ee)
            {
                panelAttention.Visible = true;
                lbAttention.Text       = "上传图片失败,原因:" + ee.Message;
                return;
            }

            //生成缩略图
            //原始图片名称
            string originalFilename = hpf.FileName;
            //生成高质量图片名称
            string strFile = Server.MapPath("~") + "/images/onsale/wear/small/small_" + Filename;

            //从文件获取图片对象
            System.Drawing.Image image = System.Drawing.Image.FromStream(hpf.InputStream, true);

            Double        Width = Double.Parse(TextBox1.Text.Trim());
            Double        Height = Double.Parse(TextBox2.Text.Trim());
            System.Double newWidth, newHeight;
            if (image.Width > image.Height)
            {
                newWidth  = Width;
                newHeight = image.Height * (newWidth / image.Width);
            }
            else
            {
                newHeight = Height;
                newWidth  = image.Width * (newHeight / image.Height);
            }
            if (newWidth > Width)
            {
                newWidth = Width;
            }
            if (newHeight > Height)
            {
                newHeight = Height;
            }
            System.Drawing.Size     size   = new System.Drawing.Size((int)newWidth, (int)newHeight); //设置图片的宽度和高度
            System.Drawing.Image    bitmap = new System.Drawing.Bitmap(size.Width, size.Height);     //新建bmp图片
            System.Drawing.Graphics g      = System.Drawing.Graphics.FromImage(bitmap);              //新建画板
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;                   //制定高质量插值法
            g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;                //设置高质量、低速度呈现平滑程度
            g.Clear(System.Drawing.Color.White);                                                     //清空画布
            //在制定位置画图
            g.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height), new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.GraphicsUnit.Pixel);


            //文字水印
            System.Drawing.Graphics testGrahpics = System.Drawing.Graphics.FromImage(bitmap);
            System.Drawing.Font     font         = new System.Drawing.Font("宋体", 10);
            System.Drawing.Brush    brush        = new System.Drawing.SolidBrush(System.Drawing.Color.Black);

            //分行
            string sInput = TextBox3.Text.Trim().ToString(); //获取输入的水印文字
            int    coloum = Convert.ToInt32(TextBox4.Text);  //获取每行的字符数
            //利用循环,来依次输出
            for (int i = 0, j = 0; i < sInput.Length; i += coloum, j++)
            {
                //若要修改水印文字在照片上的位置,可将20修改成你想要的任何值
                if (j != sInput.Length / coloum)
                {
                    string s = sInput.Substring(i, coloum);
                    testGrahpics.DrawString(s, font, brush, 20, 20 * (i / coloum + 1));
                }
                else
                {
                    string s = sInput.Substring(i, sInput.Length % coloum);
                    testGrahpics.DrawString(s, font, brush, 20, 20 * (j + 1));
                }
            }
            testGrahpics.Dispose();
            //保存缩略图c
            try
            {
                bitmap.Save(strFile, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (Exception ex)
            {
                paneInfo.Visible = true;
                lbInfo.Text      = "保存缩略图失败" + ex.Message;
            }
            //释放资源
            g.Dispose();
            bitmap.Dispose();
            image.Dispose();
        }

        Entity.PicturesItem pic = new Entity.PicturesItem();
        pic.setItemID(int.Parse(lbItemId.Text));
        // pic.setIntImageID(int.Parse(lbImageID.Text));
        pic.setBigImg("images/onsale/wear/big_" + Filename);
        pic.setSmallImg("images/onsale/wear/small/small_" + Filename);
        pic.setAlt("");

        switch (btnSubmit.Text)
        {
        case "新增":    //新增模式
            if (picture.InserItemsPic(pic))
            {
                panelSuccess.Visible = true;
                lbSuccess.Text       = "新增图片成功!";
            }
            else
            {
                panelError.Visible = true;
                lbError.Text       = "新增图片失败!";
            }
            break;

        case "修改":    //修改模式
            //int.Parse(lbImageID.Text), int.Parse(lbItemId.Text), "images/onsale/wear/big_" + Filename, "images/onsale/wear/small/small_" + Filename, ""
            if (picture.UpdatePicByID(pic))
            {
                panelSuccess.Visible = true;
                lbSuccess.Text       = "修改图片成功!";
            }
            else
            {
                panelError.Visible = true;
                lbError.Text       = "修改图片失败!";
            }
            break;
        }
    }
Exemple #35
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string     vencimento = DateTime.Now.AddMonths(1).ToShortDateString();
        sicoob_doc scd        = new sicoob_doc(true, "123456", "30/08/2007", vencimento, "38,00", "226", "1", "001", "Uisleandro CS", "CNPJ", "237", "0000", "00000", "1", "01", "N", "99", "REAL", "pagável em qualquer banco até o vencimento", "Referência: compras no site meuclick.net <br />Taxa bancária: R$ 1,50 <br />- Sr. Caixa, cobrar multa de 2% após o vencimento <br />- Em caso de dúvidas entre em contato conosco: &lt;[email protected]&gt;<br />- Emitido pelo sistema meuclick.net - &lt;http://www.meuclick.net&gt;<br />", "1,50", "", "Nome do Sacado", "000.000.000-00", "R. Tal casa tal, 100", "Euclides da Cunha", "48500-000", "BA");

        Literal_cedente_nome.Text          = scd.cedente_nome;
        Literal_agencia_Codcedente.Text    = scd.agencia + "/" + scd.codigo;
        Literal_banco_cod.Text             = "756-0";
        Literal_carteira.Text              = scd.carteira;
        Literal_documento_aceite.Text      = scd.aceite;
        Literal_documento_data.Text        = scd.data;
        Literal_documento_dataproc.Text    = DateTime.Now.ToShortDateString();      // Data de Impressão || Processamento
        Literal_documento_nossonumero.Text = scd.nossonumero;
        Literal_documento_numero.Text      = scd.numero;
        Literal_documento_especie.Text     = scd.doc_especie;
        Literal_instrucoes.Text            = scd.instrucoes;
        Literal_moeda_especie.Text         = scd.moeda_especie;
        Literal_linha_digitavel.Text       = scd.linhadigitavel;
        Literal_pagamento_local.Text       = scd.local_pagamento;
        Literal_quantidade.Text            = scd.quantidade;
        //Literal_referencia.Text = scd.referencia;
        // Sacado_Ident
        Literal_sacado_cepcidadeuf.Text = scd.sacado_cidade + " " + scd.sacado_cep + " " + scd.sacado_uf;
        Literal_sacado_cpf.Text         = " - CPF: " + scd.sacado_cpf;
        Literal_sacado_endereco.Text    = scd.sacado_endereco;
        Literal_sacado_nome.Text        = scd.sacado;
        //Literal_taxa_bancaria.Text = scd.taxa_bancaria;
        Literal_usodobanco.Text = scd.usodobanco;
        // Boletos_Ident
        Literal_valor_documento1.Text = scd.valor;
        Literal_valor_documento2.Text = scd.valor;
        Literal_vencimento_data.Text  = scd.vencimento;
        //SEGUNDA PARTE DO LAYOUT
        Literal_cedente_nome2.Text          = scd.cedente_nome;;
        Literal_agencia_Codcedente2.Text    = scd.agencia + "/" + scd.codigo;
        Literal_banco_cod2.Text             = "756-0";
        Literal_carteira2.Text              = scd.carteira;
        Literal_documento_aceite2.Text      = scd.aceite;
        Literal_documento_data2.Text        = scd.data;
        Literal_documento_dataproc2.Text    = DateTime.Now.ToShortDateString();      // Data de Impressão || Processamento
        Literal_documento_nossonumero2.Text = scd.nossonumero;
        Literal_documento_numero2.Text      = scd.numero;
        Literal_documento_especie2.Text     = scd.doc_especie;
        Literal_instrucoes2.Text            = scd.instrucoes;
        Literal_moeda_especie2.Text         = scd.moeda_especie;
        Literal_linha_digitavel2.Text       = scd.linhadigitavel;
        Literal_pagamento_local2.Text       = scd.local_pagamento;
        Literal_quantidade2.Text            = scd.quantidade;
        //Literal_referencia2.Text = scd.referencia;
        // Sacado_Ident
        Literal_sacado_cepcidadeuf2.Text = scd.sacado_cidade + " " + scd.sacado_cep + " " + scd.sacado_uf;
        Literal_sacado_cpf2.Text         = " - CPF: " + scd.sacado_cpf;
        Literal_sacado_endereco2.Text    = scd.sacado_endereco;
        Literal_sacado_nome2.Text        = scd.sacado;
        //Literal_taxa_bancaria2.Text = scd.taxa_bancaria;
        Literal_usodobanco2.Text = scd.usodobanco;
        // Boletos_Ident
        Literal_valor_documento12.Text = scd.valor;
        Literal_valor_documento22.Text = scd.valor;
        Literal_vencimento_data2.Text  = scd.vencimento;

        if (Request.QueryString[""] != null)
        {
            Response.ContentType = "image/gif";
            System.Drawing.Bitmap bt = Barras.getBarras(scd.codigodebarras);
            bt.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
        }
    }
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="stream">源图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <returns>字节数组</returns>
        public static byte[] MakeThumbnail(Stream stream, int width, int height, string mode)
        {
            System.Drawing.Image image = System.Drawing.Image.FromStream(stream);

            int towidth  = width;
            int toheight = height;

            int x  = 0;
            int y  = 0;
            int ow = image.Width;
            int oh = image.Height;

            switch (mode)
            {
            case "HW":    //指定高宽缩放(可能变形)
                break;

            case "W":    //指定宽,高按比例
                toheight = image.Height * width / image.Width;
                break;

            case "H":    //指定高,宽按比例
                towidth = image.Width * height / image.Height;
                break;

            case "Cut":    //指定高宽裁减(不变形)
                if ((double)image.Width / (double)image.Height > (double)towidth / (double)toheight)
                {
                    oh = image.Height;
                    ow = image.Height * towidth / toheight;
                    y  = 0;
                    x  = (image.Width - ow) / 2;
                }
                else
                {
                    ow = image.Width;
                    oh = image.Width * height / towidth;
                    x  = 0;
                    y  = (image.Height - oh) / 2;
                }
                break;

            default:
                break;
            }
            if (image.Width <= width && image.Height <= height)//保持原样
            {
                towidth  = image.Width;
                toheight = image.Height;
            }
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(System.Drawing.Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(image, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                        new System.Drawing.Rectangle(x, y, ow, oh),
                        System.Drawing.GraphicsUnit.Pixel);

            try
            {
                MemoryStream ms = new MemoryStream();
                //以jpg格式保存缩略图
                bitmap.Save(ms, image.RawFormat);
                return(ms.GetBuffer());
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                image.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
Exemple #37
0
        string printLabForHtmlByGrid(string modelheadfile, string modelcontentfile)
        {
            string fname = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".html";

            #region //获取模板文件内容
            string        strurlfile = HttpContext.Current.Server.MapPath("~/Model/" + modelheadfile + ".html");
            StringBuilder htmltext   = new StringBuilder(FileOper.getFileContent(strurlfile));
            int           pagecount  = Grid2.SelectedRowIndexArray.Length;
            htmltext.Replace("$pagecount", "张数:" + pagecount.ToString());

            FileStream   fs = new FileStream(HttpContext.Current.Server.MapPath("~/pdf/" + fname), FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(htmltext.ToString());
            //获取模板内容
            StringBuilder htmlcontent = new StringBuilder(FileOper.getFileContent(HttpContext.Current.Server.MapPath("~/Model/" + modelcontentfile + ".html")));
            #endregion

            try
            {
                #region 将模板内容循环添加PDF中
                SQLHelper.DbHelperSQL.SetConnectionString("");
                string sql       = "";
                int    pageindex = 1;


                // 添加文档内容
                foreach (int i in Grid2.SelectedRowIndexArray)
                {
                    htmltext.Clear();

                    if (pageindex != 1)
                    {
                        htmltext.Append("<div class='page'><br></div>");
                    }
                    htmltext.Append(htmlcontent.ToString());
                    #region //替换模板内容
                    htmltext.Replace("$orderno", Grid2.Rows[i].Values[2].ToString());
                    htmltext.Replace("$sdate", DateTime.Now.ToString("yyyyMMdd"));
                    htmltext.Replace("$remark", Grid2.Rows[i].Values[11].ToString());
                    htmltext.Replace("$itemno", Grid2.Rows[i].Values[6].ToString());
                    //htmltext.Replace("$provider", Grid1.Rows[Grid1.SelectedRowIndex].Values[5].ToString());
                    htmltext.Replace("$itemname", Grid2.Rows[i].Values[7].ToString());
                    htmltext.Replace("$spec", Grid2.Rows[i].Values[8].ToString());
                    htmltext.Replace("$quantity", Grid2.Rows[i].Values[9].ToString() + Grid2.Rows[i].Values[10].ToString());
                    sql = "select material from bomdetail   where sn=" + Grid2.Rows[i].Values[12].ToString() + "";
                    htmltext.Replace("$material", SQLHelper.DbHelperSQL.GetSingle(sql, 30));
                    sql = "select surfacedeal from bomdetail    where sn=" + Grid2.Rows[i].Values[12].ToString() + "";

                    htmltext.Replace("$codevalue", Grid2.Rows[i].Values[13].ToString());


                    htmltext.Replace("$color", SQLHelper.DbHelperSQL.GetSingle(sql, 30));
                    htmltext.Replace("$caseno", "");


                    //IDAutomation.NetAssembly.FontEncoder fe = new IDAutomation.NetAssembly.FontEncoder();
                    //htmltext.Replace("$code", fe.Code128(Grid2.Rows[i].Values[2].ToString(), 0, false));
                    //fe = null;
                    System.Threading.Thread.Sleep(5);
                    System.Drawing.Bitmap bitmap = BarcodeHelper.Generate1(Grid2.Rows[i].Values[13].ToString(), 150, 150);// CreateQRCode(str, 200, 5);
                    string s       = DateTime.Now.ToString("yyyyMMddHHmmssffff");
                    string codejpg = HttpContext.Current.Server.MapPath("~/pdf/" + s + ".bmp");
                    //image.Save(codejpg);
                    bitmap.Save(codejpg);
                    htmltext.Replace("$code", s);
                    #endregion
                    sw.WriteLine(htmltext);
                    pageindex++;
                }
                #endregion
                sw.WriteLine("</body></html>");
            }
            catch (Exception ee)
            {
                Alert.Show(ee.ToString());
            }
            finally
            {
                sw.Close();
                fs.Close();
            }
            return(fname);
        }
        /// <summary>
        /// Saves the cropped image area to a temp file, and shows a confirmation
        /// popup from where the user may accept or reject the cropped image.
        /// If they accept the new cropped image will be used as the new image source
        /// for the current canvas, if they reject the crop, the existing image will
        /// be used for the current canvas
        /// </summary>
        private void SaveCroppedImage()
        {
            if (popUpImage.Source != null)
            {
                popUpImage.Source = null;
            }

            try
            {
                _rubberBandLeft = Canvas.GetLeft(_rubberBand);
                _rubberBandTop  = Canvas.GetTop(_rubberBand);
                //create a new .NET 2.0 bitmap (which allowing saving) based on the bound bitmap url
                using (System.Drawing.Bitmap source = new System.Drawing.Bitmap(ImgUrl))
                {
                    //create a new .NET 2.0 bitmap (which allowing saving) to store cropped image in, should be
                    //same size as rubberBand element which is the size of the area of the original image we want to keep
                    using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap((int)_rubberBand.Width, (int)_rubberBand.Height))
                    {
                        //create a new destination rectange
                        System.Drawing.RectangleF recDest = new System.Drawing.RectangleF(0.0f, 0.0f, (float)bitmap.Width, (float)bitmap.Height);
                        //different resolution fix prior to cropping image
                        float hd     = 1.0f / (bitmap.HorizontalResolution / source.HorizontalResolution);
                        float vd     = 1.0f / (bitmap.VerticalResolution / source.VerticalResolution);
                        float hScale = 1.0f / (float)_zoomFactor;
                        float vScale = 1.0f / (float)_zoomFactor;
                        System.Drawing.RectangleF recSrc = new System.Drawing.RectangleF((hd * (float)_rubberBandLeft) * hScale, (vd * (float)_rubberBandTop) * vScale, (hd * (float)_rubberBand.Width) * hScale, (vd * (float)_rubberBand.Height) * vScale);
                        using (System.Drawing.Graphics gfx = System.Drawing.Graphics.FromImage(bitmap))
                        {
                            gfx.DrawImage(source, recDest, recSrc, System.Drawing.GraphicsUnit.Pixel);
                        }
                        //create a new temporary file, and delete all old ones prior to this new temp file
                        //This is is a hack that I had to put in, due to GDI+ holding on to previous
                        //file handles used by the Bitmap.Save() method the last time this method was run.
                        //This is a well known issue see http://support.microsoft.com/?id=814675 for example
                        _tempFileName = System.IO.Path.GetTempPath();
                        if (_fixedTempIdx > 2)
                        {
                            _fixedTempIdx = 0;
                        }
                        else
                        {
                            ++_fixedTempIdx;
                        }
                        //do the clean
                        CleanUp(_tempFileName, _fixedTempName, _fixedTempIdx);
                        //Due to the so problem above, which believe you me I have tried and tried to resolve
                        //I have tried the following to fix this, incase anyone wants to try it
                        //1. Tried reading the image as a strea of bytes into a new bitmap image
                        //2. I have tried to use teh WPF BitmapImage.Create()
                        //3. I have used the trick where you use a 2nd Bitmap (GDI+) to be the newly saved
                        //   image
                        //
                        //None of these worked so I was forced into using a few temp files, and pointing the
                        //cropped image to the last one, and makeing sure all others were deleted.
                        //Not ideal, so if anyone can fix it please this I would love to know. So let me know
                        _tempFileName = _tempFileName + _fixedTempName + _fixedTempIdx.ToString() + ".jpg";
                        bitmap.Save(_tempFileName, System.Drawing.Imaging.ImageFormat.Jpeg);
                        //rewire up context menu
                        _cmDragCanvas.RemoveHandler(MenuItem.ClickEvent, _cmDragCanvasRoutedEventHandler);
                        _dragCanvasForImg.ContextMenu = null;
                        _cmDragCanvas = null;
                        //create popup BitmapImage
                        BitmapImage bmpPopup = new BitmapImage(new Uri(_tempFileName));
                        popUpImage.Source          = bmpPopup;
                        grdCroppedImage.Visibility = Visibility.Visible;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 生成缩略图 (没有补白)
        /// </summary>
        /// <param name="originalImagePath">源图路径(物理路径)</param>
        /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth  = 0;
            int toheight = 0;

            if (originalImage.Width > width && originalImage.Height < height)
            {
                towidth  = width;
                toheight = originalImage.Height;
            }

            if (originalImage.Width < width && originalImage.Height > height)
            {
                towidth  = originalImage.Width;
                toheight = height;
            }
            if (originalImage.Width > width && originalImage.Height > height)
            {
                towidth  = width;
                toheight = height;
            }
            if (originalImage.Width < width && originalImage.Height < height)
            {
                towidth  = originalImage.Width;
                toheight = originalImage.Height;
            }
            int x = 0; //左上角的x坐标
            int y = 0; //左上角的y坐标


            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

            //新建一个画板
            Graphics g = System.Drawing.Graphics.FromImage(bitmap);

            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

            //清空画布并以透明背景色填充
            g.Clear(Color.Transparent);

            //在指定位置并且按指定大小绘制原图片的指定部分
            g.DrawImage(originalImage, x, y, towidth, toheight);

            try
            {
                bitmap.Save(thumbnailPath);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
        public static string MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
        {
            System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

            int towidth  = width;
            int toheight = height;

            int x  = 0;
            int y  = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;

            switch (mode)
            {
            case "HW":
                break;

            case "W":
                toheight = originalImage.Height * width / originalImage.Width;
                break;

            case "H":
                towidth = originalImage.Width * height / originalImage.Height;
                break;

            case "Cut":
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y  = 0;
                    x  = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x  = 0;
                    y  = (originalImage.Height - oh) / 2;
                }
                break;

            default:
                break;
            }


            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);


            Graphics g = System.Drawing.Graphics.FromImage(bitmap);


            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;


            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;


            g.Clear(Color.Transparent);


            g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight),
                        new Rectangle(x, y, ow, oh),
                        GraphicsUnit.Pixel);

            try
            {
                bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
            return("");
        }
    /// asp.net上传图片并生成缩略图
    /// </summary>
    /// <param name="upImage">HtmlInputFile控件</param>
    /// <param name="sSavePath">保存的路径,些为相对服务器路径的下的文件夹</param>
    /// <param name="sThumbExtension">缩略图的thumb</param>
    /// <param name="intThumbWidth">生成缩略图的宽度</param>
    /// <param name="intThumbHeight">生成缩略图的高度</param>
    /// <returns>缩略图名称</returns>
    public string UpLoadImage(HttpPostedFile myFile, string sSavePath, int intThumbWidth, int intThumbHeight)
    {
        string sFilename = "";

        if (myFile != null && myFile.ContentLength > 0)
        {
            // HttpPostedFile myFile = upImage.PostedFile;
            int nFileLen = myFile.ContentLength;
            // if (nFileLen == 0)
            //    return "没有选择上传图片";
            //获取upImage选择文件的扩展名
            string extendName = System.IO.Path.GetExtension(myFile.FileName).ToLower();
            //判断是否为图片格式
            if (extendName != ".jpg" && extendName != ".jpge" && extendName != ".gif" && extendName != ".bmp" && extendName != ".png")
            {
                return("false");
            }

            byte[] myData = new Byte[nFileLen];
            myFile.InputStream.Read(myData, 0, nFileLen);
            //保存文件名

            sFilename = DateTime.Now.ToString("yyyyMMddHHmmssffff") + extendName;   // System.IO.Path.GetFileName(myFile.FileName);

            string datetime = DateTime.Now.ToString("yyyy-MM-dd");
            if (!System.IO.Directory.Exists(sSavePath + datetime + "/"))
            {
                System.IO.Directory.CreateDirectory(sSavePath + datetime + "/");
            }

            int file_append = 0;
            //检查当前文件夹下是否有同名图片,有则在文件名+1
            while (System.IO.File.Exists(sSavePath + datetime + "/" + sFilename))
            {
                file_append++;
                sFilename = System.IO.Path.GetFileNameWithoutExtension(sFilename)
                            + file_append.ToString() + extendName;
            }
            System.IO.FileStream newFile
                = new System.IO.FileStream((sSavePath + datetime + "/" + sFilename),
                                           System.IO.FileMode.Create, System.IO.FileAccess.Write);
            newFile.Write(myData, 0, myData.Length);
            newFile.Close();
            //以上为上传原图
            try
            {
                //原图加载
                using (System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(sSavePath + datetime + "/" + sFilename))
                {
                    //原图宽度和高度
                    int width  = sourceImage.Width;
                    int height = sourceImage.Height;
                    int smallWidth;
                    int smallHeight;
                    //获取第一张绘制图的大小,(比较 原图的宽/缩略图的宽  和 原图的高/缩略图的高)
                    if (((decimal)width) / height <= ((decimal)intThumbWidth) / intThumbHeight)
                    {
                        smallWidth  = intThumbWidth;
                        smallHeight = intThumbWidth * height / width;
                    }
                    else
                    {
                        smallWidth  = intThumbHeight * width / height;
                        smallHeight = intThumbHeight;
                    }
                    //判断缩略图在当前文件夹下是否同名称文件存在
                    file_append = 0;

                    // sThumbFile =myFile.FileName ;

                    if (!System.IO.Directory.Exists(sSavePath + "thumb/" + datetime + "/"))
                    {
                        System.IO.Directory.CreateDirectory(sSavePath + "thumb/" + datetime + "/");
                    }
                    while (System.IO.File.Exists(sSavePath + "thumb/" + datetime + "/" + sFilename))
                    {
                        file_append++;
                        sFilename = System.IO.Path.GetFileNameWithoutExtension(sFilename) +
                                    file_append.ToString() + extendName;
                    }
                    //缩略图保存的绝对路径
                    string smallImagePath = sSavePath + "thumb/" + datetime + "/" + sFilename;
                    //新建一个图板,以最小等比例压缩大小绘制原图
                    using (System.Drawing.Image bitmap = new System.Drawing.Bitmap(smallWidth, smallHeight))
                    {
                        //绘制中间图
                        using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap))
                        {
                            //高清,平滑
                            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                            g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            g.Clear(Color.Black);
                            g.DrawImage(
                                sourceImage,
                                new System.Drawing.Rectangle(0, 0, smallWidth, smallHeight),
                                new System.Drawing.Rectangle(0, 0, width, height),
                                System.Drawing.GraphicsUnit.Pixel
                                );
                        }
                        //新建一个图板,以缩略图大小绘制中间图
                        using (System.Drawing.Image bitmap1 = new System.Drawing.Bitmap(intThumbWidth, intThumbHeight))
                        {
                            //绘制缩略图  http://www.cnblogs.com/sosoft/
                            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap1))
                            {
                                //高清,平滑
                                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                                g.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                                g.Clear(Color.Black);
                                int lwidth  = (smallWidth - intThumbWidth) / 2;
                                int bheight = (smallHeight - intThumbHeight) / 2;
                                g.DrawImage(bitmap, new Rectangle(0, 0, intThumbWidth, intThumbHeight), lwidth, bheight, intThumbWidth, intThumbHeight, GraphicsUnit.Pixel);
                                g.Dispose();
                                bitmap1.Save(smallImagePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                            }
                        }
                    }
                }
            }
            catch
            {
                //出错则删除
                System.IO.File.Delete((sSavePath + sFilename));
                return("false");
            }
            //返回缩略图名称
            return(sFilename);
        }
        return("false");
    }
    public static string CropImage(string ImagePath, int X1, int Y1, int X2, int Y2, int w, int h, int portalID, string userName, int userModuleID, string secureToken)
    {
        string CroppedImag             = "";
        AuthenticateService objService = new AuthenticateService();

        if (objService.IsPostAuthenticatedView(portalID, userModuleID, userName, secureToken))
        {
            string dir       = "";
            string imagename = ImagePath.Substring(ImagePath.LastIndexOf('/') + 1).ToString();
            dir = ImagePath.Replace(imagename, "");
            string imagenamewithoutext = imagename.Substring(imagename.LastIndexOf('.') + 1).ToString();

            int X     = System.Math.Min(X1, X2);
            int Y     = System.Math.Min(Y1, Y2);
            int index = 0;
            index = HttpContext.Current.Request.ApplicationPath == "/" ? 0 : 1;
            string originalFile = string.Concat(HttpContext.Current.Server.MapPath("~/"), ImagePath.Substring(ImagePath.IndexOf('/', index)).Replace("/", "\\"));
            string savePath     = Path.GetDirectoryName(originalFile) + "\\";
            if (File.Exists(originalFile))
            {
                using (System.Drawing.Image img = System.Drawing.Image.FromFile(originalFile))
                {
                    using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(w, h))
                    {
                        _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                        using (Graphics _graphic = Graphics.FromImage(_bitmap))
                        {
                            _graphic.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                            _graphic.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                            _graphic.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                            _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                            _graphic.DrawImage(img, 0, 0, w, h);
                            _graphic.DrawImage(img, new Rectangle(0, 0, w, h), X, Y, w, h, GraphicsUnit.Pixel);

                            Random rand = new Random((int)DateTime.Now.Ticks);
                            int    RandomNumber;
                            RandomNumber = rand.Next(1, 200);
                            int    CharCode   = rand.Next(Convert.ToInt32('a'), Convert.ToInt32('z'));
                            char   RandomChar = Convert.ToChar(CharCode);
                            string extension  = Path.GetExtension(originalFile);
                            //string croppedFileName = Guid.NewGuid().ToString();
                            string croppedFileName = imagenamewithoutext + "_" + RandomNumber.ToString() + RandomChar.ToString();
                            string path            = savePath;

                            // If the image is a gif file, change it into png
                            if (extension.EndsWith("gif", StringComparison.OrdinalIgnoreCase))
                            {
                                extension = ".png";
                            }

                            string newFullPathName = string.Concat(path, croppedFileName, extension);

                            using (EncoderParameters encoderParameters = new EncoderParameters(1))
                            {
                                encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                                _bitmap.Save(newFullPathName, GetImageCodec(extension), encoderParameters);
                            }

                            //lblCroppedImage.Text = string.Format("<img src='{0}' alt='Cropped image'>", path + extension);

                            CroppedImag = string.Format("<img src='{0}' alt='Cropped image'>", string.Concat(dir, croppedFileName, extension));
                        }
                    }
                }
            }
        }
        return(CroppedImag);
    }
        public void CreateChart(List <KeyValuePair <int, int> > y, string chartName, string Title, string tempFolder)
        {
            Chart         Chart1 = new Chart();
            List <string> x      = new List <string>()
            {
                "Passed", "Failed", "Stopped", "Other"
            };
            List <int> yList = (from ylist in y select ylist.Key).ToList();
            int        xAxis = 0;
            string     total = "";

            Chart1.BackColor = System.Drawing.Color.AliceBlue;
            Chart1.BackColor = System.Drawing.Color.White;
            Chart1.Series.Add(new Series());
            ChartArea a1 = new ChartArea();

            a1.Name = "Area";
            Chart1.ChartAreas.Add(a1);
            a1.InnerPlotPosition       = new ElementPosition(12, 10, 78, 78);
            Chart1.Series[0].ChartArea = "Area";
            Chart1.Series[0].Points.DataBindXY(x, yList);
            Chart1.Series["Series1"].Label          = "#VALX (#VALY)";
            Chart1.Series[0].ChartType              = SeriesChartType.Doughnut;
            Chart1.Series[0]["DoughnutRadius"]      = "20";
            Chart1.Series[0]["DoughnutInnerRadius"] = "99";
            Chart1.Series[0]["PieLabelStyle"]       = "Outside";
            Chart1.Series[0].BorderWidth            = 1;
            Chart1.Series[0].BorderDashStyle        = ChartDashStyle.Dot;
            Chart1.Series[0].BorderColor            = System.Drawing.Color.FromArgb(200, 26, 59, 105);
            foreach (KeyValuePair <int, int> l in y)
            {
                if (l.Key == 0)
                {
                    Chart1.Series[0].Points[l.Value].BorderColor       = System.Drawing.Color.White;
                    Chart1.Series["Series1"].Points[l.Value].AxisLabel = "";
                    Chart1.Series["Series1"].Points[l.Value].Label     = "";
                }
            }
            Chart1.Series[0].Points[0].Color = Chart1.Series[0].Points[0].LabelForeColor = GingerCore.General.makeColor("#008000");
            Chart1.Series[0].Points[1].Color = Chart1.Series[0].Points[1].LabelForeColor = GingerCore.General.makeColor("#FF0000");
            Chart1.Series[0].Points[2].Color = Chart1.Series[0].Points[2].LabelForeColor = GingerCore.General.makeColor("#ff57ab");
            Chart1.Series[0].Points[3].Color = Chart1.Series[0].Points[3].LabelForeColor = GingerCore.General.makeColor("#1B3651");
            Chart1.Series[0].Font            = new Font("sans-serif", 9, System.Drawing.FontStyle.Bold);
            Chart1.Height = 180;
            Chart1.Width  = 310;
            System.Drawing.SolidBrush myBrush  = new System.Drawing.SolidBrush(GingerCore.General.makeColor("#e3dfdb"));
            System.Drawing.SolidBrush myBrush1 = new System.Drawing.SolidBrush(GingerCore.General.makeColor("#1B3651"));
            Chart1.Titles.Add("NewTitle");
            Chart1.Titles["Title1"].Text      = Title;
            Chart1.Titles["Title1"].Font      = new Font("sans-serif", 11, System.Drawing.FontStyle.Bold);
            Chart1.Titles["Title1"].ForeColor = GingerCore.General.makeColor("#1B3651");
            MemoryStream m = new MemoryStream();

            Chart1.SaveImage(m, ChartImageFormat.Png);
            Bitmap   bitMapImage  = new System.Drawing.Bitmap(m);
            Graphics graphicImage = Graphics.FromImage(bitMapImage);

            graphicImage.SmoothingMode = SmoothingMode.AntiAlias;
            graphicImage.FillEllipse(myBrush, 132, 75, 50, 50);
            total = yList.Sum().ToString();
            if (total.Length == 1)
            {
                xAxis = 151;
            }
            else if (total.Length == 2)
            {
                xAxis = 145;
            }
            else if (total.Length == 3)
            {
                xAxis = 142;
            }
            else if (total.Length == 4)
            {
                xAxis = 140;
            }
            graphicImage.DrawString(yList.Sum().ToString(), new Font("sans-serif", 9, System.Drawing.FontStyle.Bold), myBrush1, new System.Drawing.Point(xAxis, 91));
            m = new MemoryStream();
            bitMapImage.Save(tempFolder + "\\" + chartName, ImageFormat.Jpeg);
            graphicImage.Dispose();
            bitMapImage.Dispose();
        }
Exemple #44
0
        /// <summary>
        /// 正方型裁剪
        /// 以图片中心为轴心,截取正方型,然后等比缩放
        /// 用于头像处理
        /// </summary>
        /// <remarks>吴剑 2012-08-08</remarks>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="fileSaveUrl">缩略图存放地址</param>
        /// <param name="side">指定的边长(正方型)</param>
        /// <param name="quality">质量(范围0-100)</param>
        public static void CutForSquare(string filePath, string fileSaveUrl, int side, int quality)
        {
            //创建目录
            string dir = Path.GetDirectoryName(fileSaveUrl);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
            System.Drawing.Image initImage = System.Drawing.Image.FromFile(filePath, true);

            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= side && initImage.Height <= side)
            {
                initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //原始图片的宽、高
                int initWidth  = initImage.Width;
                int initHeight = initImage.Height;

                //非正方型先裁剪为正方型
                if (initWidth != initHeight)
                {
                    //截图对象
                    System.Drawing.Image    pickedImage = null;
                    System.Drawing.Graphics pickedG     = null;

                    //宽大于高的横图
                    if (initWidth > initHeight)
                    {
                        //对象实例化
                        pickedImage = new System.Drawing.Bitmap(initHeight, initHeight);
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight);
                        Rectangle toR   = new Rectangle(0, 0, initHeight, initHeight);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                        //重置宽
                        initWidth = initHeight;
                    }
                    //高大于宽的竖图
                    else
                    {
                        //对象实例化
                        pickedImage = new System.Drawing.Bitmap(initWidth, initWidth);
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);
                        //设置质量
                        pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        pickedG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        //定位
                        Rectangle fromR = new Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth);
                        Rectangle toR   = new Rectangle(0, 0, initWidth, initWidth);
                        //画图
                        pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);
                        //重置高
                        initHeight = initWidth;
                    }

                    //将截图对象赋给原图
                    initImage = (System.Drawing.Image)pickedImage.Clone();
                    //释放截图资源
                    pickedG.Dispose();
                    pickedImage.Dispose();
                }

                //缩略图对象
                System.Drawing.Image    resultImage = new System.Drawing.Bitmap(side, side);
                System.Drawing.Graphics resultG     = System.Drawing.Graphics.FromImage(resultImage);
                //设置质量
                resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                resultG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //用指定背景色清空画布
                resultG.Clear(Color.White);
                //绘制缩略图
                resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel);

                //关键质量控制
                //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   ici  = null;
                foreach (ImageCodecInfo i in icis)
                {
                    if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                    {
                        ici = i;
                    }
                }
                EncoderParameters ep = new EncoderParameters(1);
                ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                //保存缩略图
                resultImage.Save(fileSaveUrl, ici, ep);

                //释放关键质量控制所用资源
                ep.Dispose();

                //释放缩略图资源
                resultG.Dispose();
                resultImage.Dispose();

                //释放原始图片资源
                initImage.Dispose();
            }
        }
Exemple #45
0
        /// <summary>
        /// 图片等比缩放
        /// </summary>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="savePath">缩略图存放地址</param>
        /// <param name="targetWidth">指定的最大宽度</param>
        /// <param name="targetHeight">指定的最大高度</param>
        /// <param name="watermarkText">水印文字(为""表示不使用水印)</param>
        /// <param name="watermarkImage">水印图片路径(为""表示不使用水印)</param>
        public static void ZoomAuto(System.IO.Stream fromFile, string savePath, System.Double targetWidth, System.Double targetHeight, string watermarkText = "", string watermarkImage = "")
        {
            //创建目录
            string dir = Path.GetDirectoryName(savePath);

            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }

            //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息)
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);
            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= targetWidth && initImage.Height <= targetHeight)
            {
                //文字水印
                if (watermarkText != "")
                {
                    using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(initImage))
                    {
                        System.Drawing.Font  fontWater  = new Font("黑体", 10);
                        System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                        gWater.Dispose();
                    }
                }

                //透明图片水印
                if (watermarkImage != "")
                {
                    if (File.Exists(watermarkImage))
                    {
                        //获取水印图片
                        using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                        {
                            //水印绘制条件:原始图片宽高均大于或等于水印图片
                            if (initImage.Width >= wrImage.Width && initImage.Height >= wrImage.Height)
                            {
                                Graphics gWater = Graphics.FromImage(initImage);

                                //透明属性
                                ImageAttributes imgAttributes = new ImageAttributes();
                                ColorMap        colorMap      = new ColorMap();
                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                                ColorMap[] remapTable = { colorMap };
                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                                float[][] colorMatrixElements =
                                {
                                    new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
                                };

                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                                gWater.DrawImage(wrImage, new Rectangle(initImage.Width - wrImage.Width, initImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);

                                gWater.Dispose();
                            }
                            wrImage.Dispose();
                        }
                    }
                }

                //保存
                initImage.Save(savePath);
            }
            else
            {
                //缩略图宽、高计算
                double newWidth  = initImage.Width;
                double newHeight = initImage.Height;

                //宽大于高或宽等于高(横图或正方)
                if (initImage.Width > initImage.Height || initImage.Width == initImage.Height)
                {
                    //如果宽大于模版
                    if (initImage.Width > targetWidth)
                    {
                        //宽按模版,高按比例缩放
                        newWidth  = targetWidth;
                        newHeight = initImage.Height * (targetWidth / initImage.Width);
                    }
                }
                //高大于宽(竖图)
                else
                {
                    //如果高大于模版
                    if (initImage.Height > targetHeight)
                    {
                        //高按模版,宽按比例缩放
                        newHeight = targetHeight;
                        newWidth  = initImage.Width * (targetHeight / initImage.Height);
                    }
                }

                //生成新图
                //新建一个bmp图片
                System.Drawing.Image newImage = new System.Drawing.Bitmap((int)newWidth, (int)newHeight);
                //新建一个画板
                System.Drawing.Graphics newG = System.Drawing.Graphics.FromImage(newImage);

                //设置质量
                newG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                newG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //置背景色
                newG.Clear(Color.White);
                //画图
                newG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, newImage.Width, newImage.Height), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);

                //文字水印
                if (watermarkText != "")
                {
                    using (System.Drawing.Graphics gWater = System.Drawing.Graphics.FromImage(newImage))
                    {
                        System.Drawing.Font  fontWater  = new Font("宋体", 10);
                        System.Drawing.Brush brushWater = new SolidBrush(Color.White);
                        gWater.DrawString(watermarkText, fontWater, brushWater, 10, 10);
                        gWater.Dispose();
                    }
                }

                //透明图片水印
                if (watermarkImage != "")
                {
                    if (File.Exists(watermarkImage))
                    {
                        //获取水印图片
                        using (System.Drawing.Image wrImage = System.Drawing.Image.FromFile(watermarkImage))
                        {
                            //水印绘制条件:原始图片宽高均大于或等于水印图片
                            if (newImage.Width >= wrImage.Width && newImage.Height >= wrImage.Height)
                            {
                                Graphics gWater = Graphics.FromImage(newImage);

                                //透明属性
                                ImageAttributes imgAttributes = new ImageAttributes();
                                ColorMap        colorMap      = new ColorMap();
                                colorMap.OldColor = Color.FromArgb(255, 0, 255, 0);
                                colorMap.NewColor = Color.FromArgb(0, 0, 0, 0);
                                ColorMap[] remapTable = { colorMap };
                                imgAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap);

                                float[][] colorMatrixElements =
                                {
                                    new float[] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f },
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f },//透明度:0.5
                                    new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f }
                                };

                                ColorMatrix wmColorMatrix = new ColorMatrix(colorMatrixElements);
                                imgAttributes.SetColorMatrix(wmColorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);
                                gWater.DrawImage(wrImage, new Rectangle(newImage.Width - wrImage.Width, newImage.Height - wrImage.Height, wrImage.Width, wrImage.Height), 0, 0, wrImage.Width, wrImage.Height, GraphicsUnit.Pixel, imgAttributes);
                                gWater.Dispose();
                            }
                            wrImage.Dispose();
                        }
                    }
                }

                //保存缩略图
                newImage.Save(savePath);

                //释放资源
                newG.Dispose();
                newImage.Dispose();
                initImage.Dispose();
            }
        }
Exemple #46
0
    static int RunAndReturnExitCode(Options opts)
    {
        if (!Directory.Exists(opts.OutputPath))
        {
            Directory.CreateDirectory(opts.OutputPath);
        }

        CASCHandler cascHandler;

        if (opts.UseOnline)
        {
            cascHandler = CASCHandler.OpenOnlineStorage(opts.OnlineProduct, opts.OnlineRegion);
        }
        else if (opts.StoragePath != null)
        {
            cascHandler = CASCHandler.OpenLocalStorage(opts.StoragePath);
        }
        else
        {
            throw new Exception("StoragePath required if not using online mode!");
        }
        cascHandler.Root.SetFlags(LocaleFlags.All_WoW, ContentFlags.None);

        foreach (var map in opts.Maps)
        {
            try
            {
                Console.WriteLine("-- processing {0}", map);

                System.Drawing.Bitmap[,] tiles = new System.Drawing.Bitmap[64, 64];
                bool[,] had_tile        = new bool[64, 64];
                bool[,] wdt_claims_tile = new bool[64, 64];

                var wdt_name = Path.Combine("world", "maps", map, String.Format("{0}.wdt", map));
                try
                {
                    using (Stream stream = cascHandler.OpenFile(wdt_name))
                    {
                        using (BinaryReader reader = new BinaryReader(stream))
                        {
                            while (reader.BaseStream.Position != reader.BaseStream.Length)
                            {
                                var magic = reader.ReadUInt32();
                                var size  = reader.ReadUInt32();
                                var pos   = reader.BaseStream.Position;

                                if (magic == mk("MPHD"))
                                {
                                    var flags = reader.ReadUInt32();

                                    if ((flags & 1) == 1)
                                    {
                                        throw new Exception("map claims to be WMO only, skipping!");
                                    }
                                }
                                else if (magic == mk("MAIN"))
                                {
                                    for (int x = 0; x < 64; ++x)
                                    {
                                        for (int y = 0; y < 64; ++y)
                                        {
                                            wdt_claims_tile[y, x] = (reader.ReadUInt32() & 1) == 1;
                                            reader.ReadUInt32();
                                        }
                                    }
                                }

                                reader.BaseStream.Position = pos + size;
                            }
                        }
                    }
                }
                catch (FileNotFoundException)
                {
                    throw new Exception(String.Format("failed loading {0}, skipping!", wdt_name));
                }

                var tile_size = 256;

                for (int x = 0; x < 64; ++x)
                {
                    for (int y = 0; y < 64; ++y)
                    {
                        had_tile[x, y] = false;

                        try
                        {
                            var blp_name = Path.Combine("world", "minimaps", map, String.Format("map{0:00}_{1:00}.blp", x, y));
                            using (Stream stream = cascHandler.OpenFile(blp_name))
                            {
                                var blp = new SereniaBLPLib.BlpFile(stream);
                                tiles[x, y] = blp.GetBitmap(0);

                                if (tiles[x, y].Height != tiles[x, y].Width)
                                {
                                    throw new Exception("non-square minimap?!");
                                }
                            }
                            had_tile[x, y] = true;
                        }
                        catch (FileNotFoundException)
                        {
                            tiles[x, y] = new System.Drawing.Bitmap(tile_size, tile_size);
                        }

                        var size_per_mcnk = tiles[x, y].Height / 16f;

                        var g = System.Drawing.Graphics.FromImage(tiles[x, y]);

                        var impassable_brush = new System.Drawing.Drawing2D.HatchBrush
                                                   (System.Drawing.Drawing2D.HatchStyle.DiagonalCross
                                                   , System.Drawing.Color.FromArgb(255 / 2, System.Drawing.Color.Yellow)
                                                   , System.Drawing.Color.FromArgb(255 / 2, System.Drawing.Color.Red)
                                                   );
                        var wdt_border_brush = new System.Drawing.Drawing2D.HatchBrush
                                                   (System.Drawing.Drawing2D.HatchStyle.DiagonalCross
                                                   , System.Drawing.Color.FromArgb(255 / 2, System.Drawing.Color.DarkBlue)
                                                   , System.Drawing.Color.FromArgb(255 / 2, System.Drawing.Color.Red)
                                                   );
                        var wdt_border_pen = new System.Drawing.Pen
                                                 (wdt_border_brush, size_per_mcnk);
                        var unreferenced_brush = new System.Drawing.Drawing2D.HatchBrush
                                                     (System.Drawing.Drawing2D.HatchStyle.DiagonalCross
                                                     , System.Drawing.Color.FromArgb(255 / 2, System.Drawing.Color.DarkBlue)
                                                     , System.Drawing.Color.FromArgb(255 / 2, System.Drawing.Color.Green)
                                                     );

                        try
                        {
                            var adt_name = Path.Combine("World", "Maps", map, String.Format("{0}_{1}_{2}.adt", map, x, y));
                            using (Stream stream = cascHandler.OpenFile(adt_name))
                            {
                                using (BinaryReader reader = new BinaryReader(stream))
                                {
                                    while (reader.BaseStream.Position != reader.BaseStream.Length)
                                    {
                                        var magic = reader.ReadUInt32();
                                        var size  = reader.ReadUInt32();
                                        var pos   = reader.BaseStream.Position;

                                        if (magic == mk("MCNK"))
                                        {
                                            var flags = reader.ReadUInt32();
                                            var sub_x = reader.ReadUInt32();
                                            var sub_y = reader.ReadUInt32();
                                            if ((flags & 2) == 2)
                                            {
                                                g.FillRectangle(impassable_brush, size_per_mcnk * sub_x, size_per_mcnk * sub_y, size_per_mcnk, size_per_mcnk);
                                            }
                                        }

                                        reader.BaseStream.Position = pos + size;
                                    }
                                }
                            }
                            had_tile[x, y] = true;
                        }
                        catch (FileNotFoundException)
                        {
                            g.FillRectangle(wdt_border_brush, 0, 0, tiles[x, y].Height, tiles[x, y].Height);
                        }

                        if (wdt_claims_tile[x, y])
                        {
                            if (x == 0 || !wdt_claims_tile[x - 1, y])
                            {
                                g.DrawLine(wdt_border_pen, 0, 0, 0, tiles[x, y].Height);
                            }
                            if (x == 63 || !wdt_claims_tile[x + 1, y])
                            {
                                g.DrawLine(wdt_border_pen, tiles[x, y].Height, 0, tiles[x, y].Height, tiles[x, y].Height);
                            }
                            if (y == 0 || !wdt_claims_tile[x, y - 1])
                            {
                                g.DrawLine(wdt_border_pen, 0, 0, tiles[x, y].Height, 0);
                            }
                            if (y == 63 || !wdt_claims_tile[x, y + 1])
                            {
                                g.DrawLine(wdt_border_pen, 0, tiles[x, y].Height, tiles[x, y].Height, tiles[x, y].Height);
                            }
                        }
                        else if (had_tile[x, y])
                        {
                            g.FillRectangle(unreferenced_brush, 0, 0, tiles[x, y].Height, tiles[x, y].Height);
                        }
                    }
                }

                int min_x = 64;
                int min_y = 64;
                int max_x = -1;
                int max_y = -1;

                for (int x = 0; x < 64; ++x)
                {
                    for (int y = 0; y < 64; ++y)
                    {
                        if (had_tile[x, y])
                        {
                            min_x = Math.Min(min_x, x);
                            min_y = Math.Min(min_y, y);
                            max_x = Math.Max(max_x, x + 1);
                            max_y = Math.Max(max_y, y + 1);
                        }
                    }
                }

                var overall          = new System.Drawing.Bitmap(tile_size * (max_x - min_x), tile_size * (max_y - min_y));
                var overall_graphics = System.Drawing.Graphics.FromImage(overall);

                for (int x = min_x; x <= max_x; ++x)
                {
                    for (int y = min_y; y <= max_y; ++y)
                    {
                        if (had_tile[x, y])
                        {
                            overall_graphics.DrawImage(tiles[x, y], (x - min_x) * tile_size, (y - min_y) * tile_size, tile_size, tile_size);
                        }
                    }
                }

                var output_file = Path.Combine(opts.OutputPath, String.Format("{0}.png", map));
                System.IO.File.Delete(output_file);
                overall.Save(output_file, System.Drawing.Imaging.ImageFormat.Png);
            }
            catch (Exception ex)
            {
                Console.WriteLine("--- {0}", ex.Message);
            }
        }

        return(0);
    }
    private void CreateCheckCodeImage(string checkCode)
    {
        if (checkCode == null || checkCode.Trim() == String.Empty)
        {
            return;
        }

        System.Drawing.Bitmap   image = new System.Drawing.Bitmap((int)Math.Ceiling((checkCode.Length * 15.0 + 40)), 23);
        System.Drawing.Graphics g     = System.Drawing.Graphics.FromImage(image);

        try
        {
            //生成随机生成器
            Random random = new Random();

            //清空图片背景色
            g.Clear(System.Drawing.Color.White);

            //画图片的背景噪音线
            for (int i = 0; i < 25; i++)
            {
                int x1 = random.Next(image.Width);
                int x2 = random.Next(image.Width);
                int y1 = random.Next(image.Height);
                int y2 = random.Next(image.Height);

                g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Silver), x1, y1, x2, y2);
            }

            System.Drawing.Font font = new System.Drawing.Font("Arial", 14, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed, 1.2f, true);

            int cySpace = 16;
            for (int i = 0; i < validateCodeCount; i++)
            {
                g.DrawString(checkCode.Substring(i, 1), font, brush, (i + 1) * cySpace, 1);
            }

            //画图片的前景噪音点
            for (int i = 0; i < 100; i++)
            {
                int x = random.Next(image.Width);
                int y = random.Next(image.Height);

                image.SetPixel(x, y, System.Drawing.Color.FromArgb(random.Next()));
            }

            //画图片的边框线
            g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1);

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/Gif";
            Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            image.Dispose();
        }
    }
    public static bool Convert(string filename, int frameDelayMS, List <System.Drawing.Bitmap> Bitmaps)
    {
        var gifEncoder = GetEncoder(ImageFormat.Gif);
        // Params of the first frame.
        var encoderParams1 = new EncoderParameters(1);

        encoderParams1.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.MultiFrame);
        // Params of other frames.
        var encoderParamsN = new EncoderParameters(1);

        encoderParamsN.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.FrameDimensionTime);
        // Params for the finalizing call.
        var encoderParamsFlush = new EncoderParameters(1);

        encoderParamsFlush.Param[0] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.Flush);

        // PropertyItem for the frame delay (apparently, no other way to create a fresh instance).
        var frameDelay = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));

        frameDelay.Id   = PropertyTagFrameDelay;
        frameDelay.Type = PropertyTagTypeLong;
        // Length of the value in bytes.
        frameDelay.Len = Bitmaps.Count * UintBytes;
        // The value is an array of 4-byte entries: one per frame.
        // Every entry is the frame delay in 1/100-s of a second, in little endian.
        frameDelay.Value = new byte[Bitmaps.Count * UintBytes];
        // E.g., here, we're setting the delay of every frame to 1 second.
        var frameDelayBytes = System.BitConverter.GetBytes((uint)frameDelayMS);

        for (int j = 0; j < Bitmaps.Count; ++j)
        {
            System.Array.Copy(frameDelayBytes, 0, frameDelay.Value, j * UintBytes, UintBytes);
        }

        // PropertyItem for the number of animation loops.
        var loopPropertyItem = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));

        loopPropertyItem.Id   = PropertyTagLoopCount;
        loopPropertyItem.Type = PropertyTagTypeShort;
        loopPropertyItem.Len  = 1;
        // 0 means to animate forever.
        loopPropertyItem.Value = System.BitConverter.GetBytes((ushort)0);

        using (var stream = new FileStream(filename + ".gif", FileMode.Create)) {
            bool first = true;
            System.Drawing.Bitmap firstBitmap = null;
            // Bitmaps is a collection of Bitmap instances that'll become gif frames.
            foreach (var bitmap in Bitmaps)
            {
                if (first)
                {
                    firstBitmap = bitmap;
                    firstBitmap.SetPropertyItem(frameDelay);
                    firstBitmap.SetPropertyItem(loopPropertyItem);
                    firstBitmap.Save(stream, gifEncoder, encoderParams1);
                    first = false;
                }
                else
                {
                    firstBitmap.SaveAdd(bitmap, encoderParamsN);
                }
            }
            firstBitmap.SaveAdd(encoderParamsFlush);
        }

        foreach (var bitmap in Bitmaps)
        {
            bitmap.Dispose();
        }

        UnityEditor.AssetDatabase.Refresh();

        return(true);
    }
Exemple #49
0
        public static void CutForCustom(string _file, string fileSaveUrl, int _fromX, int _fromY, int _tempWidth, int _tempHeight, int maxWidth, int maxHeight, int quality)
        {
            //从文件获取原始图片,并使用流中嵌入的颜色管理信息
            System.Drawing.Image initImage = System.Drawing.Image.FromFile(_file, true);

            if (_tempWidth != 0 || _tempHeight != 0)
            {
                if (_tempWidth == 0)
                {
                    _tempWidth = (int)(_tempHeight / (initImage.Height * 1.0) * initImage.Width);
                }

                if (_tempHeight == 0)
                {
                    _tempHeight = (int)(_tempWidth / (initImage.Width * 1.0) * initImage.Height);
                }
                //按模版大小生成最终图片
                System.Drawing.Image    templateImage = new System.Drawing.Bitmap(_tempWidth, _tempHeight);
                System.Drawing.Graphics templateG     = System.Drawing.Graphics.FromImage(templateImage);
                templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                templateG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                templateG.Clear(Color.White);
                templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, _tempWidth, _tempHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);
                initImage = templateImage;
            }



            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= maxWidth && initImage.Height <= maxHeight)
            {
                initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //裁剪对象
                System.Drawing.Image    pickedImage = null;
                System.Drawing.Graphics pickedG     = null;
                pickedImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                pickedG     = System.Drawing.Graphics.FromImage(pickedImage);

                //定位
                Rectangle fromR = new Rectangle(new Point(_fromX, _fromY), new Size(maxWidth, maxHeight)); //原图裁剪定位
                Rectangle toR   = new Rectangle(new Point(0, 0), new Size(maxWidth, maxHeight));           //目标定位


                //设置质量
                pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                pickedG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                //裁剪
                pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);

                //按模版大小生成最终图片
                System.Drawing.Image    templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                System.Drawing.Graphics templateG     = System.Drawing.Graphics.FromImage(templateImage);
                templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                templateG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                templateG.Clear(Color.White);
                templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel);

                //关键质量控制
                //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo   ici  = null;
                foreach (ImageCodecInfo i in icis)
                {
                    if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                    {
                        ici = i;
                    }
                }
                EncoderParameters ep = new EncoderParameters(1);
                ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                //保存缩略图
                //if (Directory.Exists(fileSaveUrl))
                //{
                templateImage.Save(fileSaveUrl, ici, ep);
                //}

                #region 保存图片到硬盘

                //final_image.Save(MapPath(_path));
                #endregion
                //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);

                //释放资源
                templateG.Dispose();
                templateImage.Dispose();

                pickedG.Dispose();
                pickedImage.Dispose();
            }

            //释放资源
            initImage.Dispose();
        }
Exemple #50
0
    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="originalImagePath">源图路径(物理路径)</param>
    /// <param name="thumbnailPath">缩略图路径(物理路径)</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    /// <param name="mode">生成缩略图的方式</param>
    public static void MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath);

        int towidth  = width;
        int toheight = height;

        int x  = 0;
        int y  = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;

        switch (mode)
        {
        case "HW":    //指定高宽缩放(可能变形)
            break;

        case "W":    //指定宽,高按比例
            toheight = originalImage.Height * width / originalImage.Width;
            break;

        case "H":    //指定高,宽按比例
            towidth = originalImage.Width * height / originalImage.Height;
            break;

        case "Cut":    //指定高宽裁减(不变形)
            if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
            {
                oh = originalImage.Height;
                ow = originalImage.Height * towidth / toheight;
                y  = 0;
                x  = (originalImage.Width - ow) / 2;
            }
            else
            {
                ow = originalImage.Width;
                oh = originalImage.Width * height / towidth;
                x  = 0;
                y  = (originalImage.Height - oh) / 2;
            }
            break;

        default:
            break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

        //新建一个画板
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

        //设置高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //清空画布并以透明背景色填充
        g.Clear(System.Drawing.Color.Transparent);

        //在指定位置并且按指定大小绘制原图片的指定部分
        g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight),
                    new System.Drawing.Rectangle(x, y, ow, oh),
                    System.Drawing.GraphicsUnit.Pixel);

        try
        {
            //以jpg格式保存缩略图
            bitmap.Save(thumbnailPath, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
        }
    }
    public ArrayList batUpload()
    {
        //string shopName = "";
        //string strSQL = "select shopName from T_Shop_User where shopid=(select ProviderInfo from T_Goods_info where goodsid='" + goodsId + "' and Datafrom='ShopSeller');select memberName from T_member_info where memberId=(select ProviderInfo from T_Goods_info where goodsid='" + goodsId + "' and Datafrom='PersonSeller');";

        //DataSet ds = adohelper.ExecuteSqlDataset(strSQL);
        //if (ds == null || ds.Tables.Count < 2)
        //    return null;

        //if (ds.Tables[0].Rows.Count > 0)
        //    shopName = ds.Tables[0].Rows[0][0].ToString();
        //else
        //    shopName = ds.Tables[1].Rows[0][0].ToString();

        ArrayList list      = new ArrayList();
        AdoHelper adohelper = AdoHelper.CreateHelper(StarTech.Util.AppConfig.DBInstance);
        //搜集表单中的file元素
        HttpFileCollection files = Request.Files;

        //遍历file元素
        for (int i = 0; i < files.Count; i++)
        {
            HttpPostedFile       postedFile = files[i];
            HtmlInputCheckBox [] ck         = { Checkbox1, Checkbox2, Checkbox3, Checkbox4 };
            if (postedFile.FileName != "")
            {
                //文件大小
                int fileSize = postedFile.ContentLength / 1024;
                if (fileSize == 0)
                {
                    fileSize = 1;
                }

                //提取文件名
                string oldFileName = Path.GetFileName(postedFile.FileName);

                //提取文件扩展名
                string oldFileExt = Path.GetExtension(oldFileName);

                //重命名文件
                string newFileName = Guid.NewGuid().ToString() + oldFileExt;

                //设置保存目录
                string webDirectory  = "/upload/goodsadmin/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                string saveDirectory = Server.MapPath(webDirectory);
                if (!Directory.Exists(saveDirectory))
                {
                    Directory.CreateDirectory(saveDirectory);
                }

                //设置保存路径
                string savePath = saveDirectory + newFileName;
                //保存
                postedFile.SaveAs(savePath);

                string savePath2    = savePath;
                string newFileName2 = newFileName;
                if (ck[i].Checked)
                {
                    //System.Drawing.Image nowImg = System.Drawing.Image.FromFile(savePath);
                    System.Drawing.Bitmap nowImg2 = new System.Drawing.Bitmap(savePath);
                    System.Drawing.Bitmap nowImg  = new System.Drawing.Bitmap(nowImg2.Width, nowImg2.Height);

                    float x = nowImg.Width - 50;
                    float y = nowImg.Height - 30;

                    System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(nowImg);
                    g.DrawImage(nowImg2, 0, 0);
                    System.Drawing.Font  f = new System.Drawing.Font("华文彩云", 12);
                    System.Drawing.Brush b = new System.Drawing.SolidBrush(System.Drawing.Color.Black);
                    g.DrawString("才通天下微信公号", f, b, x, y);
                    f = new System.Drawing.Font("华文琥珀", 12);
                    b = new System.Drawing.SolidBrush(System.Drawing.Color.White);
                    g.DrawString("才通天下微信公号·", f, b, x, y);
                    f.Dispose();
                    b.Dispose();
                    g.Dispose();
                    nowImg2.Dispose();
                    //savePath2 = webDirectory + newFileName.Replace(oldFileExt, "" + oldFileExt);
                    string nGuid = Guid.NewGuid().ToString();
                    nGuid        = nGuid.Replace(nGuid[new Random().Next(1, 9)], nGuid[new Random().Next(10, 15)]);
                    newFileName2 = nGuid + oldFileExt;
                    savePath2    = webDirectory + newFileName2;
                    MemoryStream ms = new MemoryStream();
                    nowImg.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                    byte[] imgData = ms.ToArray();
                    File.Delete(savePath);
                    FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.ReadWrite);
                    if (fs != null)
                    {
                        fs.Write(imgData, 0, imgData.Length);
                        fs.Close();
                    }
                    nowImg.Dispose();
                }



                //缩略图
                MakeSmallPic(Server.MapPath(webDirectory + newFileName), Server.MapPath(webDirectory + newFileName.Replace(oldFileExt, ".jpg")));
                string goodsSmallPic = webDirectory + newFileName.Replace(oldFileExt, "" + oldFileExt);

                list.Add(oldFileName + "|" + fileSize + "|" + goodsSmallPic);
            }
        }
        return(list);
    }
Exemple #52
0
    //ÏÈ´æ·Åµ½ÄÚ´æÖÐ
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Drawing.Image    thumbnail_image = null; //ËõÂÔͼ
        System.Drawing.Image    original_image  = 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
            original_image = System.Drawing.Image.FromStream(jpeg_image_upload.InputStream);

            // Calculate the new width and height
            int width = original_image.Width;
            int height = original_image.Height;
            int target_width = 100;
            int target_height = 100;
            int new_width, new_height;

            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

            // Old way
            //thumbnail_image = original_image.GetThumbnailImage(new_width, new_height, null, System.IntPtr.Zero);
            // We don't have to create a Thumbnail 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 it 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;             /* new way */
            //graphic.DrawImage(thumbnail_image, paste_x, paste_y, new_width, new_height);
            graphic.DrawImage(original_image, 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 Thumbnail object
            string    thumbnail_id = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            Thumbnail thumb        = new Thumbnail(thumbnail_id, ms.GetBuffer());

            // Put it all in the Session (initialize the session if necessary)
            List <Thumbnail> thumbnails = Session["file_info"] as List <Thumbnail>;
            if (thumbnails == null)
            {
                thumbnails = new List <Thumbnail>();
            }
            thumbnails.Add(thumb);
            Session["file_info"] = thumbnails;
            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 (original_image != null)
            {
                original_image.Dispose();
            }
            if (thumbnail_image != null)
            {
                thumbnail_image.Dispose();
            }
            if (ms != null)
            {
                ms.Close();
            }
            Response.End();
        }
    }
Exemple #53
0
        public IEnumerable <SingleFileProgress> Print(string fontFullname, int maxTextureWidth)
        {
            int      count    = this.ttfTexture.CharInfoDict.Count;
            FileInfo fileInfo = new FileInfo(fontFullname);

            int width;
            int height;
            {
                System.Drawing.Bitmap bigBitmap = this.ttfTexture.BigBitmap;
                width  = bigBitmap.Width;
                height = bigBitmap.Height;
            }

            const int magicNumber = 100;

            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(this.outputWidth,
                                                                     (this.ttfTexture.FontHeight + 1) * magicNumber); //this.ttfTexture.CharInfoDict.Count);
            Graphics g = Graphics.FromImage(bitmap);

            int index = 0;

            foreach (var item in this.ttfTexture.CharInfoDict)
            {
                char                  c                   = item.Key;
                CharacterInfo         info                = item.Value;
                System.Drawing.Bitmap singleGlyph         = new Bitmap(info.width, info.height);
                Graphics              singleGlyphGraphics = Graphics.FromImage(singleGlyph);
                g.DrawImage(this.ttfTexture.BigBitmap,
                            new Rectangle(1, (index % magicNumber) * (this.ttfTexture.FontHeight + 1),
                                          info.width, this.ttfTexture.FontHeight),
                            new Rectangle(info.xoffset, info.yoffset - info.yoffset % this.ttfTexture.FontHeight,
                                          info.width, this.ttfTexture.FontHeight), GraphicsUnit.Pixel);
                g.DrawString(string.Format("{0}/{1}: offset: [{2}, {3}] size: [{4}, {5}], texCoord: [{6}, {7}, {8}, {9}]",
                                           index, c, info.xoffset, info.yoffset, info.width, info.height,
                                           (float)info.xoffset / (float)width,
                                           (float)info.yoffset / (float)height,
                                           (float)(info.xoffset + info.width) / (float)width,
                                           (float)(info.yoffset + ttfTexture.FontHeight) / (float)height), font, brush,
                             info.width + 1, (index % magicNumber) * (this.ttfTexture.FontHeight + 1)
                             );
                index++;

                if (index % magicNumber == 0)
                {
                    g.Dispose();
                    bitmap.Save(fontFullname + "list" + index / magicNumber + ".png");
                    bitmap.Dispose();

                    bitmap = new System.Drawing.Bitmap(this.outputWidth,
                                                       (this.ttfTexture.FontHeight + 1) * magicNumber); //this.ttfTexture.CharInfoDict.Count);
                    g = Graphics.FromImage(bitmap);
                }


                yield return(new SingleFileProgress()
                {
                    progress = (index * magicNumber / count),
                    message = string.Format("print PNG list for {0}", fileInfo.Name),
                });
            }

            g.Dispose();
            bitmap.Save(fontFullname + "list" + index / magicNumber + ".png");
            bitmap.Dispose();

            yield return(new SingleFileProgress()
            {
                progress = magicNumber,
                message = string.Format("print PNG list for {0} done!", fileInfo.Name),
            });
        }
        public override Bitmap Generate(System.Drawing.Bitmap bitmap, int newWidth, int newHeight)
        {
            string fileName       = Path.GetRandomFileName();
            string originFileName = fileName + ".bmp";
            string resultFileName = fileName + "_result.bmp";

            bitmap.Save(originFileName, ImageFormat.Bmp);
            string inputFileName  = Path.GetFullPath(originFileName);
            string outputFileName = Path.GetFullPath(resultFileName);

            int energyFuncTypeInt;

            switch (EnergyFuncType)
            {
            default:
            case EnergyFuncType.Prewitt:
                energyFuncTypeInt = 0;
                break;

            case EnergyFuncType.V1:
                energyFuncTypeInt = 1;
                break;

            case EnergyFuncType.VSquare:
                energyFuncTypeInt = 2;
                break;

            case EnergyFuncType.Sobel:
                energyFuncTypeInt = 3;
                break;

            case EnergyFuncType.Laplacian:
                energyFuncTypeInt = 4;
                break;
            }

            int    threadCount = Parallelization ? Math.Min(4, Environment.ProcessorCount) : 1;
            string parameters  = string.Format("-I \"{0}\" -O \"{1}\" -X {2} -Y {3} -R {4} -C {5} -E {6} -T {7}",
                                               inputFileName, outputFileName, newWidth, newHeight, Hd ? 6 : 0, energyFuncTypeInt, ForwardEnergy ? 1 : 0, threadCount);

            ProcessStartInfo startInfo = new ProcessStartInfo(CairAppFileName, parameters);

            startInfo.UseShellExecute = false;
            startInfo.CreateNoWindow  = true;
            Process proc = Process.Start(startInfo);

            proc.Start();
            proc.WaitForExit();

            Bitmap   result = null;
            FileInfo outputFileInfo;

            using (MemoryStream stream = new MemoryStream())
            {
                outputFileInfo = new FileInfo(outputFileName);
                while (IsFileLocked(outputFileInfo))
                {
                    Thread.Sleep(LockAwaitingMs);
                }
                using (FileStream fs = File.OpenRead(outputFileName))
                {
                    fs.CopyTo(stream);
                }
                result = new Bitmap(stream);
            }

            File.Delete(inputFileName);
            outputFileInfo = new FileInfo(outputFileName);
            while (IsFileLocked(outputFileInfo))
            {
                Thread.Sleep(LockAwaitingMs);
            }
            outputFileInfo.Delete();

            return(result);
        }
Exemple #55
0
 public void Save(string path, ImageCodecInfo encoder, EncoderParameters parameters)
 {
     // FIXME: Workaround
     using (Bitmap b = new Bitmap(this))
         b.Save(path, encoder, parameters);
 }
Exemple #56
0
        /// <summary>
        /// 指定长宽裁剪
        /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸
        /// </summary>
        /// <remarks>吴剑 2012-08-08</remarks>
        /// <param name="fromFile">原图Stream对象</param>
        /// <param name="fileSaveUrl">保存路径</param>
        /// <param name="maxWidth">最大宽(单位:px)</param>
        /// <param name="maxHeight">最大高(单位:px)</param>
        /// <param name="quality">质量(范围0-100)</param>
        public static void CutForCustom(System.IO.Stream fromFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality)
        {
            //从文件获取原始图片,并使用流中嵌入的颜色管理信息
            System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true);

            //原图宽高均小于模版,不作处理,直接保存
            if (initImage.Width <= maxWidth && initImage.Height <= maxHeight)
            {
                initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
            else
            {
                //模版的宽高比例
                double templateRate = (double)maxWidth / maxHeight;
                //原图片的宽高比例
                double initRate = (double)initImage.Width / initImage.Height;

                //原图与模版比例相等,直接缩放
                if (templateRate == initRate)
                {
                    //按模版大小生成最终图片
                    System.Drawing.Image    templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG     = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel);
                    templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);
                }
                //原图与模版比例不等,裁剪后缩放
                else
                {
                    //裁剪对象
                    System.Drawing.Image    pickedImage = null;
                    System.Drawing.Graphics pickedG     = null;

                    //定位
                    Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位
                    Rectangle toR   = new Rectangle(0, 0, 0, 0); //目标定位

                    //宽为标准进行裁剪
                    if (templateRate > initRate)
                    {
                        //裁剪对象实例化
                        pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)System.Math.Floor(initImage.Width / templateRate));
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);

                        //裁剪源定位
                        fromR.X      = 0;
                        fromR.Y      = (int)System.Math.Floor((initImage.Height - initImage.Width / templateRate) / 2);
                        fromR.Width  = initImage.Width;
                        fromR.Height = (int)System.Math.Floor(initImage.Width / templateRate);

                        //裁剪目标定位
                        toR.X      = 0;
                        toR.Y      = 0;
                        toR.Width  = initImage.Width;
                        toR.Height = (int)System.Math.Floor(initImage.Width / templateRate);
                    }
                    //高为标准进行裁剪
                    else
                    {
                        pickedImage = new System.Drawing.Bitmap((int)System.Math.Floor(initImage.Height * templateRate), initImage.Height);
                        pickedG     = System.Drawing.Graphics.FromImage(pickedImage);

                        fromR.X      = (int)System.Math.Floor((initImage.Width - initImage.Height * templateRate) / 2);
                        fromR.Y      = 0;
                        fromR.Width  = (int)System.Math.Floor(initImage.Height * templateRate);
                        fromR.Height = initImage.Height;

                        toR.X      = 0;
                        toR.Y      = 0;
                        toR.Width  = (int)System.Math.Floor(initImage.Height * templateRate);
                        toR.Height = initImage.Height;
                    }

                    //设置质量
                    pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    pickedG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

                    //裁剪
                    pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel);

                    //按模版大小生成最终图片
                    System.Drawing.Image    templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight);
                    System.Drawing.Graphics templateG     = System.Drawing.Graphics.FromImage(templateImage);
                    templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
                    templateG.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    templateG.Clear(Color.White);
                    templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel);

                    //关键质量控制
                    //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff
                    ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo   ici  = null;
                    foreach (ImageCodecInfo i in icis)
                    {
                        if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif")
                        {
                            ici = i;
                        }
                    }
                    EncoderParameters ep = new EncoderParameters(1);
                    ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);

                    //保存缩略图
                    //if (Directory.Exists(fileSaveUrl))
                    //{
                    templateImage.Save(fileSaveUrl, ici, ep);
                    //}

                    #region 保存图片到硬盘

                    //final_image.Save(MapPath(_path));
                    #endregion
                    //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg);

                    //释放资源
                    templateG.Dispose();
                    templateImage.Dispose();

                    pickedG.Dispose();
                    pickedImage.Dispose();
                }
            }

            //释放资源
            initImage.Dispose();
        }
        private static void MakeThumbnail(HttpPostedFile m_PostedFile, string SaveAsFileName, int width, int height)
        {
            //获取图片类型
            string            fileExtension     = System.IO.Path.GetExtension(m_PostedFile.FileName).ToLower();
            ImageCodecInfo    encoderInfo       = GetEncoderInfoByMimeType_static(fileExtension);
            EncoderParameter  encoderParameter  = new EncoderParameter(Encoder.Quality, 90L);
            EncoderParameters encoderParameters = new EncoderParameters(1);

            encoderParameters.Param[0] = encoderParameter;
            //获取原始图片
            System.Drawing.Image originalImage = System.Drawing.Image.FromStream(m_PostedFile.InputStream);
            //缩略图画布宽高
            int towidth  = width;
            int toheight = height;
            //原始图片写入画布坐标和宽高(用来设置裁减溢出部分)
            int x  = 0;
            int y  = 0;
            int ow = originalImage.Width;
            int oh = originalImage.Height;
            //原始图片画布,设置写入缩略图画布坐标和宽高(用来原始图片整体宽高缩放)
            int bg_x = 0;
            int bg_y = 0;
            int bg_w = towidth;
            int bg_h = toheight;
            //倍数变量
            double multiple = 0;

            //获取宽长的或是高长与缩略图的倍数
            if (originalImage.Width >= originalImage.Height)
            {
                multiple = (double)originalImage.Width / (double)width;
            }
            else
            {
                multiple = (double)originalImage.Height / (double)height;
            }
            //上传的图片的宽和高小等于缩略图
            if (ow <= width && oh <= height)
            {
                //缩略图按原始宽高
                bg_w = originalImage.Width;
                bg_h = originalImage.Height;
                //空白部分用背景色填充
                bg_x = Convert.ToInt32(((double)towidth - (double)ow) / 2);
                bg_y = Convert.ToInt32(((double)toheight - (double)oh) / 2);
            }
            //上传的图片的宽和高大于缩略图
            else
            {
                //宽高按比例缩放
                bg_w = Convert.ToInt32((double)originalImage.Width / multiple);
                bg_h = Convert.ToInt32((double)originalImage.Height / multiple);
                //空白部分用背景色填充
                bg_y = Convert.ToInt32(((double)height - (double)bg_h) / 2);
                bg_x = Convert.ToInt32(((double)width - (double)bg_w) / 2);
            }
            //新建一个bmp图片,并设置缩略图大小.
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空画布并设置背景色
            g.Clear(System.Drawing.ColorTranslator.FromHtml("#F2F2F2"));
            //在指定位置并且按指定大小绘制原图片的指定部分

            //第一个System.Drawing.Rectangle是原图片的画布坐标和宽高,第二个是原图片写在画布上的坐标和宽高,最后一个参数是指定数值单位为像素
            g.DrawImage(originalImage, new System.Drawing.Rectangle(bg_x, bg_y, bg_w, bg_h), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);
            //水印
            g.CompositingMode    = CompositingMode.SourceOver;
            g.CompositingQuality = CompositingQuality.HighQuality;
            //Image stamp = Image.FromFile(@"C:\Documents and Settings\Administrator\My Documents\My Pictures\zanque.jpg");
            //g.DrawImage(stamp, 5, 5, stamp.Width, stamp.Height);
            //stamp.Dispose();
            Image stamp = Image.FromFile(System.Web.HttpContext.Current.Server.MapPath("\\watermark\\foot.png"));

            g.DrawImage(stamp, 120 - stamp.Width, 150 - stamp.Height - 2, stamp.Width, stamp.Height);
            stamp.Dispose();
            try
            {
                bitmap.Save(SaveAsFileName, encoderInfo, encoderParameters);
            }
            catch (System.Exception e)
            {
                throw e;
            }
            finally
            {
                originalImage.Dispose();
                bitmap.Dispose();
                g.Dispose();
            }
        }
Exemple #58
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int    Width   = 0;
        int    Height  = 0;
        double centerX = 0;
        double centerY = 0;
        double Zoom    = 0;

        string[] Layer;

        //Parse request parameters
        if (!int.TryParse(Request.Params["WIDTH"], out Width))
        {
            throw(new ArgumentException("Invalid parameter"));
        }
        if (!int.TryParse(Request.Params["HEIGHT"], out Height))
        {
            throw (new ArgumentException("Invalid parameter"));
        }
        if (!double.TryParse(Request.Params["ZOOM"], System.Globalization.NumberStyles.Float, numberFormat_EnUS, out Zoom))
        {
            throw (new ArgumentException("Invalid parameter"));
        }
        if (!double.TryParse(Request.Params["X"], System.Globalization.NumberStyles.Float, numberFormat_EnUS, out centerX))
        {
            throw (new ArgumentException("Invalid parameter"));
        }
        if (!double.TryParse(Request.Params["Y"], System.Globalization.NumberStyles.Float, numberFormat_EnUS, out centerY))
        {
            throw (new ArgumentException("Invalid parameter"));
        }
        if (Request.Params["MAP"] == null)
        {
            throw (new ArgumentException("Invalid parameter"));
        }
        if (!string.IsNullOrEmpty(Request.Params["Layers"]))
        {
            Layer = Request.Params["Layers"].Split(new char[] { ',' });
        }
        else
        {
            throw (new ArgumentException("Invalid parameter"));
        }

        string colors     = Request.Params["Colors"];
        string colorsLine = Request.Params["ColorsLine"];

        //Params OK
        SharpMap.Map map = InitializeMap(Request.Params["MAP"], new System.Drawing.Size(Width, Height), colors, colorsLine);
        if (map == null)
        {
            throw (new ArgumentException("Invalid map"));
        }

        //toggle layers
        if (Layer[0] != "none")
        {
            for (int i = 0; i < Layer.Length; i++)
            {
                toggleLayer(Layer[i], map).Enabled = false;
            }
        }


        //Set visible map extents
        map.Center = new GeoAPI.Geometries.Coordinate(centerX, centerY);
        map.Zoom   = Zoom;



        //Generate map
        System.Drawing.Bitmap img = (System.Drawing.Bitmap)map.GetMap();

        //Stream the image to the client
        Response.ContentType = "image/png";
        System.IO.MemoryStream MS = new System.IO.MemoryStream();
        img.Save(MS, System.Drawing.Imaging.ImageFormat.Png);

        // tidy up
        img.Dispose();
        byte[] buffer = MS.ToArray();
        Response.OutputStream.Write(buffer, 0, buffer.Length);
    }
    protected void Button4_Click(object sender, EventArgs e)//הוספת פריט חדש אל קטגוריה נבחרת
    {
        XmlDocument myDoc = new XmlDocument();

        myDoc.Load(MapPath("trees/XMLFile.xml"));
        int     selectedCategory = Convert.ToInt16(ListBox1.SelectedValue);
        string  myGameNum        = Convert.ToString(Session["theItemIdSessions"]);
        XmlNode myCategory       = myDoc.SelectSingleNode("//Game[@id='" + myGameNum + "']").ChildNodes.Item(selectedCategory);
        string  fileType         = "";

        if (TextBox2.Visible == false)
        {
            fileType = FileUpload1.PostedFile.ContentType;
        }
        if (RadioButtonList1.SelectedValue == "txt")
        {
            FileUpload1.Visible = false;
            Image1.Visible      = false;
            XmlElement myParit = myDoc.CreateElement("parit");
            XmlText    myText  = myDoc.CreateTextNode(TextBox2.Text);
            myParit.AppendChild(myText);
            myParit.SetAttribute("type", "text");
            myCategory.AppendChild(myParit);

            int ParitCount = Convert.ToInt16(myCategory.SelectSingleNode("@paritcounter").Value);
            ParitCount++;

            string newParitCount = ParitCount.ToString();
            myCategory.SelectSingleNode("@paritcounter").Value = newParitCount;

            myDoc.Save(MapPath("trees/XMLFile.xml"));
            int noPritim = myCategory.ChildNodes.Count - 1;
            Panel1.Controls.Clear();
            GeneratePritim(noPritim);
            TextBox2.Text = "";
            checkForPublish();
            ViewState["selectedCategory"] = selectedCategory;

            updateListBox1();
            ListBox1.SelectedValue = ViewState["selectedCategory"].ToString();
        }

        if (RadioButtonList1.SelectedValue == "pic")
        {
            FileUpload1.Visible = true;
            Image1.ImageUrl     = "";
            Image1.Visible      = true;
            //שמירת הנתיב המלא של הקובץ
            string fileName = FileUpload1.PostedFile.FileName;
            // הסיומת של הקובץ
            string endOfFileName = fileName.Substring(fileName.LastIndexOf("."));
            String myTime        = DateTime.Now.ToString("dd_MM_yy - HH_mm_ss");
            //שמירת השעה על השרת
            // חיבור השם החדש עם הסיומת של הקובץ
            string imageNewName = "imageNewName" + myTime + endOfFileName;           //שמירה של הקובץ לספרייה בשם החדש שלו


            FileUpload1.PostedFile.SaveAs(Server.MapPath(imagesLibPath) + imageNewName);
            System.Drawing.Image bitmap;
            using (var bmpTemp = new System.Drawing.Bitmap(Server.MapPath(imagesLibPath) + imageNewName))
            {
                bitmap = new System.Drawing.Bitmap(bmpTemp);
            }
            bitmap = FixedSize(bitmap, 217, 140);
            bitmap.Save(Server.MapPath(imagesLibPath) + imageNewName);
            //Image1.ImageUrl = imagesLibPath + imageNewName;
            XmlElement myParit = myDoc.CreateElement("parit");
            XmlText    myText  = myDoc.CreateTextNode(imagesLibPath + imageNewName.ToString());
            myParit.AppendChild(myText);
            myParit.SetAttribute("type", "pic");
            myCategory.AppendChild(myParit);


            int ParitCount = Convert.ToInt16(myCategory.SelectSingleNode("@paritcounter").Value);
            ParitCount++;

            string newParitCount = ParitCount.ToString();
            myCategory.SelectSingleNode("@paritcounter").Value = newParitCount;

            myDoc.Save(MapPath("trees/XMLFile.xml"));
            int noPritim = myCategory.ChildNodes.Count - 1;
            Panel1.Controls.Clear();
            GeneratePritim(noPritim);
            TextBox2.Text = "";
            checkForPublish();
            ViewState["selectedCategory"] = selectedCategory;

            updateListBox1();
            ListBox1.SelectedValue = ViewState["selectedCategory"].ToString();
        }


        else
        {
            // הקובץ אינו תמונה ולכן לא ניתן להעלות אותו
        }
        FileUpload1.Visible            = false;
        RadioButtonList1.SelectedValue = "txt";
        XmlNodeList myCategorys  = myDoc.SelectNodes("//Game[@id='" + myGameNum + "']/Category");
        XmlNode     mygame       = myDoc.SelectSingleNode("//Game[@id='" + myGameNum + "']");
        bool        paritok      = true;
        int         counCategory = myCategorys.Count;

        if (mygame.Attributes["categorycounter"].Value != "4")
        {
            Button6.Visible = true;
            TextBox1.Text   = "";
        }
        for (int i = 0; i < counCategory; i++)
        {
            if ((Convert.ToInt16(mygame.ChildNodes.Item(i).Attributes["paritcounter"].Value) < 5))
            {
                paritok = false;
            }
        }
        if (paritok == true)
        {
            MinP.ForeColor = System.Drawing.Color.Green;
        }
    }
Exemple #60
-12
        public static string Create(string src, int? width, int? height)
        {
            var sourcePath = HttpContext.Current.Server.MapPath(src);
            if (string.IsNullOrEmpty(sourcePath) || !File.Exists(sourcePath))
            {
                return string.Empty;
            }
            using (var srcBitmap = new Bitmap(sourcePath))
            {
                var w = width.HasValue ? width.Value : srcBitmap.Width;
                var h = height.HasValue ? height.Value : srcBitmap.Height;

                var imagePath = generatePath(sourcePath, w, h);
                var mappedImagePath = HttpContext.Current.Server.MapPath(imagePath);
                if (File.Exists(mappedImagePath))
                {
                    return imagePath;
                }

                using (var destBitmap = new Bitmap(srcBitmap, new Size(w, h)))
                {
                    destBitmap.Save(mappedImagePath);
                    return imagePath;
                }
            }
        }