protected void Page_Load(object sender, EventArgs e) { string _s1 = Request.QueryString[0]; //string _s2 = Request.QueryString[1]; System.Drawing.Image _img = null; Graphics _gra = null; _img = new Bitmap(400, 60); _gra = Graphics.FromImage(_img); _gra.Clear(Color.White); _gra.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; _gra.TextRenderingHint = TextRenderingHint.AntiAlias; // try to install the font //_gra.RotateTransform(-3); _gra.DrawString(_s1, new Font("Freestyle Script", 25, FontStyle.Underline | FontStyle.Bold), Brushes.Black, 6, 11); //_gra.DrawString(_s2, new Font("Freestyle Script", 18, FontStyle.Bold), Brushes.Black, 510, 10); _gra.RotateTransform(3); //_gra.DrawString("Basic Demographics", new Font("Tw Cen MT Condensed", 17), Brushes.Olive, 300, 40); EncoderParameters _ens = new EncoderParameters(1); _ens.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100); _img.Save(Response.OutputStream, ImageCodecInfo.GetImageEncoders()[1], _ens); _gra.Dispose(); _img.Dispose(); }
public static void Change() { Bitmap myBitmap; ImageCodecInfo myImageCodecInfo; Encoder myEncoder; EncoderParameter myEncoderParameter; EncoderParameters myEncoderParameters; // Create a Bitmap object based on a BMP file. myBitmap = new Bitmap(@"D:\Shapes.jpg"); // Get an ImageCodecInfo object that represents the JPEG codec. myImageCodecInfo = GetEncoderInfo("image/jpeg"); // Create an Encoder object based on the GUID // for the Quality parameter category. myEncoder = Encoder.Quality; // Create an EncoderParameters object. // An EncoderParameters object has an array of EncoderParameter // objects. In this case, there is only one // EncoderParameter object in the array. myEncoderParameters = new EncoderParameters(1); // Save the bitmap as a JPEG file with quality level 25. myEncoderParameter = new EncoderParameter(myEncoder, 25L); myEncoderParameters.Param[0] = myEncoderParameter; myBitmap.Save(@"c:\temp.jpg", myImageCodecInfo, myEncoderParameters); Byte[] bytes = File.ReadAllBytes(@"c:\temp.jpg"); // Save the bitmap as a JPEG file with quality level 50. //myEncoderParameter = new EncoderParameter(myEncoder, 50L); //myEncoderParameters.Param[0] = myEncoderParameter; //myBitmap.Save(@"D:\Shapes050.jpg", myImageCodecInfo, myEncoderParameters); //// Save the bitmap as a JPEG file with quality level 75. //myEncoderParameter = new EncoderParameter(myEncoder, 75L); //myEncoderParameters.Param[0] = myEncoderParameter; //myBitmap.Save(@"D:\Shapes075.jpg", myImageCodecInfo, myEncoderParameters); }
public static void Main(string[] args) { //get the codec for tiff files ImageCodecInfo info = null; Bitmap pages = null; foreach(ImageCodecInfo ice in ImageCodecInfo.GetImageEncoders()) if(ice.MimeType=="image/tiff") info = ice; if (info == null) { Console.WriteLine ("Couldn't get codec for image/tiff"); return; } //use the save encoder Encoder enc = Encoder.SaveFlag; EncoderParameters ep=new EncoderParameters(1); ep.Param[0] = new EncoderParameter (enc,(long)EncoderValue.MultiFrame); pages = (Bitmap) Image.FromFile ("../../Test/System.Drawing/bitmaps/almogaver32bits.bmp"); pages.Save ("out.tiff", info, ep); //save second frame ep.Param[0] = new EncoderParameter (enc,(long)EncoderValue.FrameDimensionPage); Bitmap bm=(Bitmap)Image.FromFile ("../../Test/System.Drawing/bitmaps/nature24bits.jpg"); pages.SaveAdd (bm,ep); ep.Param[0] = new EncoderParameter (enc,(long)EncoderValue.Flush); pages.SaveAdd (ep); }
protected void Page_Load(object sender, EventArgs e) { if (Request.Form["width"] != null && Request.Form["width"] != String.Empty) { // image dimensions int width = Int32.Parse((Request.Form["width"].IndexOf('.') != -1) ? Request.Form["width"].Substring(0, Request.Form["width"].IndexOf('.')) : Request.Form["width"]); int height = Int32.Parse((Request.Form["height"].IndexOf('.') != -1) ? Request.Form["height"].Substring(0, Request.Form["height"].IndexOf('.')) : Request.Form["height"]); // image Bitmap result = new Bitmap(width, height); // set pixel colors for (int y = 0; y < height; y++) { // column counter for the row int x = 0; // get current row data string[] row = Request.Form["r" + y].Split(new char[]{','}); // set pixels in the row for (int c = 0; c < row.Length; c++) { // get pixel color and repeat count string[] pixel = row[c].Split(new char[] { ':' }); Color current_color = ColorTranslator.FromHtml("#" + pixel[0]); int repeat = pixel.Length > 1 ? Int32.Parse(pixel[1]) : 1; // set pixel(s) for (int l = 0; l < repeat; l++) { result.SetPixel(x, y, current_color); x++; } } } // output image // image type Response.ContentType = "image/jpeg"; // find image encoder for selected type ImageCodecInfo[] encoders; ImageCodecInfo img_encoder = null; encoders = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo codec in encoders) if (codec.MimeType == Response.ContentType) { img_encoder = codec; break; } // image parameters EncoderParameter jpeg_quality = new EncoderParameter(Encoder.Quality, 100L); // for jpeg images only EncoderParameters enc_params = new EncoderParameters(1); enc_params.Param[0] = jpeg_quality; result.Save(Response.OutputStream, img_encoder, enc_params); } }
public static void SaveToJpeg(Bitmap bitmap, string filePath, long qualityPercent) { ImageCodecInfo imageCodecInfo = GetEncoderInfo("image/jpeg"); Encoder encoder = Encoder.Quality; EncoderParameters encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(encoder, qualityPercent); bitmap.Save(filePath, imageCodecInfo, encoderParameters); }
public void Page_Load(Object sender, EventArgs e) { try{ //Get the width and height from form width = Int32.Parse(Request["width"]); height = Int32.Parse(Request["height"]); }catch(Exception ex){ //If the width and height has not been given, we cannot create the image. Response.Write("Image width and height not provided."); Response.End(); } //Background color, request and set default bgcolor = Request["bgcolor"]; if (bgcolor=="" || bgcolor==null){ bgcolor = "FFFFFF"; } //Conver the bg color in ASP.NET format bgColor = ColorTranslator.FromHtml("#" + bgcolor); //Decompress the data //data = decompress(Request["data"]); data = (Request["data"]); //Parse data rows = new String[height+1]; rows = data.Split(';'); //Build the image now buildBitmap(); //Output it now Response.ContentType = "image/jpeg"; Response.AddHeader("Content-Disposition", "attachment; filename=\"FusionCharts.jpg\""); //Now, we need to encode the image using an encoder. //Find the encoder. ImageCodecInfo[] encoders; ImageCodecInfo img_encoder = null; encoders = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo codec in encoders){ if (codec.MimeType == Response.ContentType){ img_encoder = codec; break; } } //Set the quality as 100 EncoderParameter jpeg_quality = new EncoderParameter(Encoder.Quality, 100L); EncoderParameters enc_params = new EncoderParameters(1); //Convey the parameter enc_params.Param[0] = jpeg_quality; //Save to output stream after applying proper encoders chart.Save(Response.OutputStream, img_encoder, enc_params); //Dispose the bitmap gr.Dispose(); chart.Dispose(); }
public void Save(string saveTo) { using (Bitmap bmp = new Bitmap(_stream, true)) { using (Bitmap newBmp = new Bitmap(bmp, new Size(_width, _height))) { long quality = _quality; Encoder encoder = Encoder.Quality; EncoderParameters parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(encoder, quality); newBmp.Save(saveTo, GetEncoderInfo("image/jpeg"), parameters); } } }
public static void SaveJpeg(string path, Image image, int quality) { if ((quality < 0) || (quality > 100)) { string error = string.Format("Jpeg image quality must be between 0 and 100, with 100 being the highest quality. A value of {0} was specified.", quality); throw new ArgumentOutOfRangeException(error); } EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg"); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; image.Save(path, jpegCodec, encoderParams); }
public static void SaveJpeg(string path, System.Drawing.Image img, int quality, string typeS) { if (quality < 0 || quality > 100) throw new ArgumentOutOfRangeException("quality must be between 0 and 100."); // Encoder parameter for image quality EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality); // Jpeg image codec ImageCodecInfo jpegCodec = GetEncoderInfo(typeS); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; img.Save(path, jpegCodec, encoderParams); }
public static Stream SaveAsJpeg(this Image img, int quality = 90) { MemoryStream ms = new MemoryStream(); ImageCodecInfo myImageCodecInfo; System.Drawing.Imaging.Encoder myEncoder; EncoderParameter myEncoderParameter; EncoderParameters myEncoderParameters; myImageCodecInfo = GetEncoderInfo("image/jpeg"); myEncoder = System.Drawing.Imaging.Encoder.Quality; myEncoderParameters = new EncoderParameters(1); myEncoderParameter = new EncoderParameter(myEncoder, quality); myEncoderParameters.Param[0] = myEncoderParameter; img.Save(ms, myImageCodecInfo, myEncoderParameters); return ms; }
public static byte[] GetBitmapBytes(Bitmap source) { //Settings to increase quality of the image ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[4]; EncoderParameters parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L); //Temporary stream to save the bitmap using (MemoryStream tmpStream = new MemoryStream()) { source.Save(tmpStream, codec, parameters); //Get image bytes from temporary stream byte[] result = new byte[tmpStream.Length]; tmpStream.Seek(0, SeekOrigin.Begin); tmpStream.Read(result, 0, (int)tmpStream.Length); return result; } }
/// <summary> /// Method to resize, convert and save the image. /// </summary> /// <param name="image">Bitmap image.</param> /// <param name="maxWidth">resize width.</param> /// <param name="maxHeight">resize height.</param> /// <param name="quality">quality setting value.</param> /// <param name="filePath">file path.</param> public void Save(Bitmap image, int maxWidth, int maxHeight, int quality, string filePath) { // Get the image's original width and height int originalWidth = image.Width; int originalHeight = image.Height; // To preserve the aspect ratio float ratioX = (float)maxWidth / (float)originalWidth; float ratioY = (float)maxHeight / (float)originalHeight; float ratio = Math.Min(ratioX, ratioY); // New width and height based on aspect ratio int newWidth = (int)(originalWidth * ratio); int newHeight = (int)(originalHeight * ratio); // Convert other formats (including CMYK) to RGB. Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb); // Draws the image in the specified size with quality mode set to HighQuality using (Graphics graphics = Graphics.FromImage(newImage)) { graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.DrawImage(image, 0, 0, newWidth, newHeight); } // Get an ImageCodecInfo object that represents the JPEG codec. ImageCodecInfo imageCodecInfo = this.GetEncoderInfo(ImageFormat.Jpeg); // Create an Encoder object for the Quality parameter. Encoder encoder = Encoder.Quality; // Create an EncoderParameters object. EncoderParameters encoderParameters = new EncoderParameters(1); // Save the image as a JPEG file with quality level. EncoderParameter encoderParameter = new EncoderParameter(encoder, quality); encoderParameters.Param[0] = encoderParameter; newImage.Save(filePath, imageCodecInfo, encoderParameters); }
//protected static readonly object trimmingLockObject = new System.Object(); public byte[] ПолучитьФайлПросмотр(object id_file, ImageType type, int width, int height, ImageFormat format, long Качество, КонструкторИзображения Конструктор, string domain) { #region FileName var data = new DataClient(); var path = Path.Combine(System.Configuration.ConfigurationManager.AppSettings["ПросмотрХранилище"], domain); var filename = null as string; switch (format) { case ImageFormat.Jpg: { filename = string.Format("{0:f0}_{1:0}x{2:0}_{3}_{4}_{5}.jpg", id_file, width, height, type.ToString(), Качество, Path.GetFileNameWithoutExtension(data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain))); } break; case ImageFormat.Png: { filename = string.Format("{0:f0}_{1:0}x{2:0}_{3}_{4}.png", id_file, width, height, type.ToString(), Path.GetFileNameWithoutExtension(data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain))); } break; } #endregion var full_filename = Path.Combine(path, filename); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } if (System.IO.File.Exists(full_filename)) { return(System.IO.File.ReadAllBytes(full_filename)); } else { var imgOutput = null as Bitmap; var canvas = null as Graphics; try { using (var output = new MemoryStream()) { try { var image = null as Bitmap; var filestream = ПолучитьФайлПолностью(id_file, Хранилище.Оперативное, domain); if (filestream != null) { using (var mc = new MemoryStream(filestream)) using (image = new Bitmap(mc)) { #region очистить фон if (Конструктор != null && Конструктор.ПрозрачныйФон) { var firstPixelColor = image.GetPixel(0, 0); if (firstPixelColor != null && Color.Transparent.ToArgb() != firstPixelColor.ToArgb()) { var floodFiller = new UnsafeQueueLinearFloodFiller() { Bitmap = new PictureBoxScroll.EditableBitmap(image, PixelFormat.Format32bppArgb), FillColor = Color.Transparent, Tolerance = new byte[] { 5, 5, 5 } }; floodFiller.FloodFill(new Point(0, 0)); if (floodFiller.Bitmap != null && floodFiller.Bitmap.Bitmap != null) { image.Dispose(); image = new Bitmap(floodFiller.Bitmap.Bitmap); } } } #endregion #region trimming if (Конструктор != null && Конструктор.ОбрезатьПустоеМесто) { // Find the min/max non-white/transparent pixels var min = new Point(int.MaxValue, int.MaxValue); var max = new Point(int.MinValue, int.MinValue); var isAlpha = image.PixelFormat.HasFlag(PixelFormat.Alpha); for (int x = 0; x < image.Width; ++x) { for (int y = 0; y < image.Height; ++y) { var pixelColor = image.GetPixel(x, y); if ((pixelColor.R < 245 && pixelColor.G < 245 && pixelColor.B < 245 && pixelColor.A > 0) || (isAlpha && pixelColor.A > 0)) { if (x < min.X) { min.X = x; } if (y < min.Y) { min.Y = y; } if (x > max.X) { max.X = x; } if (y > max.Y) { max.Y = y; } } } } var cropRectangle = new Rectangle(min.X, min.Y, max.X - min.X, max.Y - min.Y); var newBitmap = new Bitmap(cropRectangle.Width, cropRectangle.Height); newBitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution); var g = Graphics.FromImage(newBitmap); g.DrawImage(image, 0, 0, cropRectangle, GraphicsUnit.Pixel); g.Flush(); image.Dispose(); image = newBitmap; } #endregion var newSize = new Size(width, height); switch (type) { case ImageType.Full: { newSize = new Size(width, height); imgOutput = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb); canvas = Graphics.FromImage(imgOutput); canvas.SmoothingMode = SmoothingMode.Default; canvas.CompositingQuality = CompositingQuality.HighQuality; canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; if (format == ImageFormat.Jpg) { canvas.Clear(Color.White); } canvas.DrawImage(image, 0, 0, newSize.Width, newSize.Height); canvas.Flush(); } break; case ImageType.Thumbnail: { int _width = Math.Min(image.Size.Height, image.Size.Width); imgOutput = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb); canvas = Graphics.FromImage(imgOutput); canvas.SmoothingMode = SmoothingMode.Default; canvas.CompositingQuality = CompositingQuality.HighQuality; canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; if (format == ImageFormat.Jpg) { canvas.Clear(Color.White); } canvas.DrawImage(image, new Rectangle(0, 0, newSize.Width, newSize.Height), new Rectangle(0, 0, _width, _width), GraphicsUnit.Pixel); canvas.Flush(); } break; case ImageType.Resize: { if (newSize.Width > 0 && newSize.Height == 0) // Сжатие по ширине (принудительное) { newSize.Height = (int)(((double)newSize.Width / (double)image.Size.Width) * image.Size.Height); } else if (newSize.Width == 0 && newSize.Height > 0) // Сжатие по высоте (принудительное) { newSize.Width = (int)(((double)newSize.Height / (double)image.Size.Height) * image.Size.Width); } else { int sourceWidth = image.Size.Width; int sourceHeight = image.Size.Height; float nPercent = 0; float nPercentW = 0; float nPercentH = 0; nPercentW = ((float)newSize.Width / (float)sourceWidth); nPercentH = ((float)newSize.Height / (float)sourceHeight); if (nPercentH < nPercentW) { nPercent = nPercentH; } else { nPercent = nPercentW; } newSize = new Size((int)(sourceWidth * nPercent), (int)(sourceHeight * nPercent)); } imgOutput = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb); canvas = Graphics.FromImage(imgOutput); canvas.SmoothingMode = SmoothingMode.Default; canvas.CompositingQuality = CompositingQuality.HighQuality; canvas.InterpolationMode = InterpolationMode.HighQualityBicubic; if (format == ImageFormat.Jpg) { canvas.Clear(Color.White); } canvas.DrawImage(image, 0, 0, newSize.Width, newSize.Height); canvas.Flush(); } break; } #region Добавить слои из конструктора if (Конструктор != null && Конструктор.Слои != null && canvas != null) { foreach (var item in Конструктор.Слои) { if (item.id_file == null || item.id_file.Equals(0m)) { continue; } using (var mcLayer = new MemoryStream(ПолучитьФайлПолностью(item.id_file, Хранилище.Оперативное, domain))) using (var imageLayer = new Bitmap(mcLayer)) { canvas.DrawImage(imageLayer, item.x, item.y, Convert.ToInt32(imageLayer.Width * (item.width > 0 ? item.width : 1.0)), Convert.ToInt32(imageLayer.Height * (item.height > 0 ? item.height : 1.0))); } } } #endregion } } else { imgOutput = new Bitmap(width, height); canvas = Graphics.FromImage(imgOutput); canvas.Clear(Color.White); canvas.DrawRectangle(Pens.Gray, 0, 0, width - 1, height - 1); canvas.DrawString( "Not Found " + data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain), new Font("Tahoma", 8), Brushes.Gray, new RectangleF(0, 0, width, height), new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }); } } catch (Exception ex) { imgOutput = new Bitmap(width, height); canvas = Graphics.FromImage(imgOutput); canvas.Clear(Color.White); canvas.DrawRectangle(Pens.Gray, 0, 0, width - 1, height - 1); canvas.DrawString( data.ПолучитьЗначение <string>(id_file, "НазваниеОбъекта", Хранилище.Оперативное, domain), new Font("Tahoma", 8), Brushes.Gray, new RectangleF(0, 0, width, height), new StringFormat() { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center }); ConfigurationClient.WindowsLog("FileService", string.Empty, domain, ex.ToString()); } #region Вывод switch (format) { case ImageFormat.Jpg: { var ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Качество); ImageCodecInfo imageCodecInfo = null; foreach (ImageCodecInfo item in ImageCodecInfo.GetImageEncoders()) { if (item.MimeType == "image/jpeg") { imageCodecInfo = item; break; } } imgOutput.Save(output, imageCodecInfo, ep); } break; case ImageFormat.Png: { imgOutput.Save(output, System.Drawing.Imaging.ImageFormat.Png); } break; } //сохранить файл System.IO.File.WriteAllBytes(full_filename, output.ToArray()); #endregion return(output.ToArray()); } } finally { if (canvas != null) { canvas.Dispose(); } if (imgOutput != null) { imgOutput.Dispose(); } } } }
protected void Page_Load(object sender, EventArgs e) { string ImageR = Request.QueryString["ID"]; string widthR = Request.QueryString["W"]; string heightR = Request.QueryString["H"]; string imageName = ""; int width = 0; int height = 0; int Image = 0; if (string.IsNullOrEmpty(ImageR) || string.IsNullOrEmpty(widthR) || string.IsNullOrEmpty(heightR)) { return; } try { width = Convert.ToInt32(widthR); height = Convert.ToInt32(heightR); Image = Convert.ToInt32(ImageR); } catch (Exception exc) { log.Error("Ocurrió un error al obtener los datos enviados para el ResizeImage. " + exc); } if (width == 0 || height == 0) { return; } int widthWM = (int)(width / 3); int heightWM = (int)(height / 3); Bitmap bmp = null; if (string.IsNullOrEmpty(ImageR)) { System.Drawing.Image imgDefault = System.Drawing.Image.FromFile(Server.MapPath("~/Images/Home.png")); imageName = "Magri_Turismo"; bmp = new Bitmap(imgDefault); } else { DocumentFile theOfferImage = DocumentFileBLL.GetDocumentFile(Image); if (theOfferImage == null) { return; } string pathImage = theOfferImage.FileStoragePath; FileInfo fileImage = new FileInfo(pathImage); if (fileImage.Exists) { imageName = theOfferImage.Name + theOfferImage.Extension; System.Drawing.Image img = System.Drawing.Image.FromFile(pathImage); if (img != null) { bmp = ImageUtilities.CreateThumbnail(img, width, height); } } } if (bmp == null) { return; } //Bitmap bmpImage = ImageUtilities.CreateThumbnail(bmp, width, height); //if (bmpImage == null) // return; decimal quality = Math.Max(0, Math.Min(100, ImageUtilities.getQuality(width, height))); ImageCodecInfo[] Info = ImageCodecInfo.GetImageEncoders(); EncoderParameters Params = new EncoderParameters(1); Params.Param[0] = new EncoderParameter(Encoder.Quality, Convert.ToInt64(quality)); int type = 1; if (ImageR.Equals("1")) { type = 4; } Response.ContentType = Info[type].MimeType; Response.AddHeader("Content-Disposition", "attachment;Filename=\"" + imageName + "\""); using (MemoryStream stream = new MemoryStream()) { bmp.Save(stream, Info[type], Params); stream.WriteTo(Response.OutputStream); } }
protected void btnCrop_Click(object sender, EventArgs e) { int X1 = Convert.ToInt32(Request.Form["x1"]); int Y1 = Convert.ToInt32(Request["y1"]); int X2 = Convert.ToInt32(Request.Form["x2"]); int Y2 = Convert.ToInt32(Request.Form["y2"]); int X = System.Math.Min(X1, X2); int Y = System.Math.Min(Y1, Y2); int w = Convert.ToInt32(Request.Form["w"]); int h = Convert.ToInt32(Request.Form["h"]); // That can be any image type (jpg,jpeg,png,gif) from any where in the local server string originalFile = Server.MapPath(Global.PROFILE_PICTURE + Session["SignUpUserId"].ToString() + ".jpg"); string newFullPathName = null; using (Image img = 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); string extension = Path.GetExtension(originalFile); //string croppedFileName = Guid.NewGuid().ToString(); string croppedFileName = Session["SignUpUserId"].ToString(); string path = Server.MapPath("cropped/"); // If the image is a gif file, change it into png if (extension.EndsWith("gif", StringComparison.OrdinalIgnoreCase)) { extension = ".jpg"; } newFullPathName = string.Concat(path, croppedFileName, extension); /* if (File.Exists(originalFile)) { File.Delete(originalFile); } File.Create(newFullPathName); */ //string oldfile = newFullPathName; //string newfile = Server.MapPath(Global.PROFILE_PICTURE) + Session["UserId"] + ".jpg"; //string backup = Server.MapPath(Global.PROFILE_PICTURE) +"backup.jpg"; // if (System.IO.File.Exists(newfile)) //{ // //System.IO.File.Delete(newfile); //} using (EncoderParameters encoderParameters = new EncoderParameters(1)) { encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L); _bitmap.Save(newFullPathName, GetImageCodec(extension), encoderParameters); } // lblCroppedImage.Text = string.Format("<img src='profileimages/{0}' alt='Cropped image'>", croppedFileName + extension); } } } if (File.Exists(originalFile)) { File.Delete(originalFile); } if (File.Exists(newFullPathName)) { File.Move(newFullPathName, originalFile); } }
public static void ProcessImage(Stream istm, Stream ostm, ProcessImageSettings s) { using (var img = Image.FromStream(istm, true, false)) { if (s.FrameIndex > 0) { var fd = img.RawFormat.Guid == ImageFormat.Gif.Guid ? FrameDimension.Time : FrameDimension.Page; if (img.GetFrameCount(fd) > s.FrameIndex) { img.SelectActiveFrame(fd, s.FrameIndex); } else { throw new ArgumentOutOfRangeException("Invalid Frame Index"); } } img.ExifRotate(); s = s.Clone(); s.Fixup(img.Width, img.Height); bool alpha = ((ImageFlags)img.Flags & ImageFlags.HasAlpha) == ImageFlags.HasAlpha; var src = img; var crop = s.Crop; if (s.HybridScaleRatio > 1d) { int intw = (int)Math.Ceiling(img.Width / s.HybridScaleRatio); int inth = (int)Math.Ceiling(img.Height / s.HybridScaleRatio); var bmp = new Bitmap(intw, inth); using (var gfx = Graphics.FromImage(bmp)) { gfx.PixelOffsetMode = PixelOffsetMode.Half; gfx.CompositingMode = CompositingMode.SourceCopy; gfx.DrawImage(img, Rectangle.FromLTRB(0, 0, intw, inth), crop.X, crop.Y, crop.Width, crop.Height, GraphicsUnit.Pixel); } img.Dispose(); src = bmp; crop = new Rectangle(0, 0, intw, inth); } using (src) using (var iat = new ImageAttributes()) using (var bmp = new Bitmap(s.Width, s.Height, alpha ? GdiPixelFormat.Format32bppArgb : GdiPixelFormat.Format24bppRgb)) using (var gfx = Graphics.FromImage(bmp)) { iat.SetWrapMode(WrapMode.TileFlipXY); gfx.PixelOffsetMode = PixelOffsetMode.Half; gfx.CompositingMode = CompositingMode.SourceCopy; gfx.InterpolationMode = InterpolationMode.HighQualityBicubic; if (alpha && !s.MatteColor.IsEmpty) { gfx.Clear(s.MatteColor); gfx.CompositingMode = CompositingMode.SourceOver; gfx.CompositingQuality = CompositingQuality.GammaCorrected; } gfx.DrawImage(src, Rectangle.FromLTRB(0, 0, s.Width, s.Height), crop.X, crop.Y, crop.Width, crop.Height, GraphicsUnit.Pixel, iat); switch (s.SaveFormat) { case FileFormat.Bmp: bmp.Save(ostm, ImageFormat.Bmp); break; case FileFormat.Tiff: using (var encoderParams = new EncoderParameters(1)) using (var param = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionNone)) { encoderParams.Param[0] = param; bmp.Save(ostm, tiffCodec, encoderParams); } break; case FileFormat.Jpeg: using (var encoderParams = new EncoderParameters(1)) using (var param = new EncoderParameter(Encoder.Quality, s.JpegQuality)) { encoderParams.Param[0] = param; bmp.Save(ostm, jpegCodec, encoderParams); } break; default: if (s.IndexedColor) { bmp.Save(ostm, ImageFormat.Gif); } else { bmp.Save(ostm, ImageFormat.Png); } break; } } } }
public static void saveJpeg(string path, Bitmap img) { // Encoder parameter for image quality EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, 85L); // Jpeg image codec ImageCodecInfo jpegCodec = getEncoderInfo("image/jpeg"); if (jpegCodec == null) return; EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; img.Save(path, jpegCodec, encoderParams); }
/// <summary> /// 无损压缩图片 /// </summary> /// <param name="src">原图片文件流</param> /// <param name="dest">压缩后图片文件流</param> /// <param name="quality">压缩质量(数字越小压缩率越高)1-100</param> /// <param name="size">压缩后图片的最大大小</param> /// <param name="sfsc">是否是第一次调用</param> /// <returns></returns> public static bool CompressImage(Stream src, Stream dest, byte quality = 90, int size = 1024, bool sfsc = true) { //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true if (sfsc && src.Length < size * 1024) { src.CopyTo(dest); return(true); } using Image iSource = Image.FromStream(src); int dHeight = iSource.Height; int dWidth = iSource.Width; int sW, sH; //按比例缩放 Size temSize = new Size(iSource.Width, iSource.Height); if (temSize.Width > dHeight || temSize.Width > dWidth) { if ((temSize.Width * dHeight) > (temSize.Width * dWidth)) { sW = dWidth; sH = (dWidth * temSize.Height) / temSize.Width; } else { sH = dHeight; sW = (temSize.Width * dHeight) / temSize.Height; } } else { sW = temSize.Width; sH = temSize.Height; } using Bitmap bmpp = new Bitmap(dWidth, dHeight); using Graphics g = Graphics.FromImage(bmpp); g.Clear(Color.WhiteSmoke); g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); //以下代码为保存图片时,设置压缩质量 using var ep = new EncoderParameters(); using var eParam = new EncoderParameter(Encoder.Quality, new long[] { quality }); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegIcIinfo = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG")); if (jpegIcIinfo != null) { bmpp.Save(dest, jpegIcIinfo, ep);//dFile是压缩后的新路径 if (dest.Length > 1024 * size && quality > 10) { quality -= 10; CompressImage(src, dest, quality, size, false); } } else { bmpp.Save(dest, iSource.RawFormat); } return(true); } catch { return(false); } }
protected void Page_Load(object sender, EventArgs e) { try { double proporcao; int w, h, xCrop, yCrop; string imgName = Request.QueryString["img"]; byte crop = Convert.ToByte(Request.QueryString["c"]); string colorName = Request.QueryString["b"]; int interpolationMode = Convert.ToInt16(Request.QueryString["i"]); //Precisão do redimensionamento int p = Convert.ToInt32(Request.QueryString["p"]); int widthT = Convert.ToInt32(Request.QueryString["w"]); int heightT = Convert.ToInt32(Request.QueryString["h"]); //Nome da imagem a ser cacheada ou comparada string strImg = imgName.Substring(0, imgName.LastIndexOf('.')) + "_" + widthT + "x" + heightT + "_" + crop.ToString() + (string.IsNullOrEmpty(colorName) ? "" : "_" + colorName) + "_" + interpolationMode + "_" + p + imgName.Substring(imgName.LastIndexOf('.')); //Path com as imagens "cacheadas" string cachePath = Path.Combine(Server.MapPath("~/Arquivos/ThumbCache/"), strImg); //Dados da última DateTime dataModCache = File.GetLastWriteTime(Server.MapPath(imgName)); DateTime dataModImg = File.GetLastWriteTime(cachePath); int comparacao = DateTime.Compare(dataModCache, dataModImg); //Se o arquivo já existe no cache if (File.Exists(cachePath) && comparacao <= 0) { OutputCacheResponse(HttpContext.Current, File.GetLastWriteTime(cachePath)); HttpContext.Current.Response.WriteFile(cachePath); return; } else { //Cria diretório com as imagens (parâmetro) Directory.CreateDirectory(Path.GetDirectoryName(cachePath)); //Deleta se já existe imagem cacheada if (File.Exists(cachePath)) { File.Delete(cachePath); } //Cria o "bitmap" com imagem original string imgPath = HttpContext.Current.Request.MapPath("~/" + imgName); Bitmap bmp = new Bitmap(imgPath); ImageFormat formato = bmp.RawFormat; double widthO = bmp.Size.Width; double heightO = bmp.Size.Height; //Caso só largura ou altura sejam transmitidas if (widthT == 0 || heightT == 0) { //Cálculo com base na largura (widthT) if (widthT > 0) { heightO = widthT / (widthO / heightO); widthO = widthT; heightT = Convert.ToInt32(heightO); //Cálculo com base na altura (heightT) } else { widthO = heightT / (heightO / widthO); heightO = heightT; widthT = Convert.ToInt32(widthO); } } else { //Caso opção seja "CROPAR" if (crop == 1) { //Se uma das medidas originais forem MAIORES que o "Target" if (widthO > widthT || heightO > heightT) { proporcao = widthO / heightO; while (widthO > widthT || heightO > heightT) { widthO--; heightO = widthO / proporcao; if (widthO <= widthT && heightO <= heightT) { break; } } } //Se uma das medidas originais forem MENORES que o "Target" if (widthO < widthT || heightO < heightT) { proporcao = widthO / heightO; while (widthO < widthT || heightO < heightT) { widthO++; heightO = widthO / proporcao; if (widthO >= widthT && heightO >= heightT) { break; } } } } else { //Se uma das medidas originais forem MAIORES que o "Target" if (widthO > widthT || heightO > heightT) { proporcao = widthO / heightO; while (widthO > widthT || heightO > heightT) { widthO--; heightO = widthO / proporcao; if (widthO <= widthT && heightO <= heightT) { break; } } } else { //Se uma das medidas originais forem MENORES que o "Target" if (widthO < widthT || heightO < heightT) { proporcao = widthO / heightO; while (widthO < widthT && heightO < heightT) { widthO++; heightO = widthO / proporcao; if (widthO >= widthT && heightO >= heightT) { break; } } } } } } //Medidas finais (incluindo valor de precisão) w = Convert.ToInt32(widthO) + p; h = Convert.ToInt32(heightO) + p; //Calcula as coordenadas para corte xCrop = Convert.ToInt32((w - widthT) / 2); yCrop = Convert.ToInt32((h - heightT) / 2); Bitmap bmpT = new Bitmap(widthT, heightT); EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, 95L); //Image codec ImageCodecInfo imgCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(a => a.FormatID == formato.Guid); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; //Cor de fundo Color bg = Color.White; //Caso a cor não seja transmitida if (string.IsNullOrEmpty(colorName)) { //se PNG "transparent" if (formato.Equals(ImageFormat.Png) || formato.Equals(ImageFormat.Gif)) bg = Color.Transparent; } else { try { //Html color (hex) bg = ColorTranslator.FromHtml("#" + colorName); } catch (Exception) { //Html color bg = ColorTranslator.FromHtml(colorName); } } //Manipula e salva em cache using (Graphics g = Graphics.FromImage(bmpT)) { g.CompositingQuality = CompositingQuality.HighSpeed; g.InterpolationMode = interpolationMode == 0 ? InterpolationMode.HighQualityBicubic : InterpolationMode.HighQualityBilinear; g.CompositingMode = CompositingMode.SourceCopy; g.Clear(bg); g.DrawImage(bmp, -xCrop, -yCrop, w, h); using (MemoryStream memoryStream = new MemoryStream()) { bmpT.Save(memoryStream, imgCodec, encoderParams); OutputCacheResponse(HttpContext.Current, File.GetLastWriteTime(imgPath)); using (FileStream diskCacheStream = new FileStream(cachePath, FileMode.CreateNew)) { memoryStream.WriteTo(diskCacheStream); } memoryStream.WriteTo(HttpContext.Current.Response.OutputStream); } } bmp.Dispose(); bmpT.Dispose(); } } catch (Exception ex) { Font font = new Font("verdana", 12); Bitmap bmp = new Bitmap(ex.Message.Length * 10, 50); Graphics g = Graphics.FromImage(bmp); g.DrawString(ex.Message.Replace("'", ""), font, new SolidBrush(Color.White), new PointF(5.0F, 5.0F)); bmp.Save(Response.OutputStream, ImageFormat.Jpeg); g.Dispose(); bmp.Dispose(); } }
/// <summary> /// 指定长宽裁剪 /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸 /// </summary> /// <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(this Stream fromFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality) { //从文件获取原始图片,并使用流中嵌入的颜色管理信息 using var initImage = Image.FromStream(fromFile, true); //原图宽高均小于模版,不作处理,直接保存 if ((initImage.Width <= maxWidth) && (initImage.Height <= maxHeight)) { initImage.Save(fileSaveUrl); } else { //模版的宽高比例 double templateRate = (double)maxWidth / maxHeight; //原图片的宽高比例 double initRate = (double)initImage.Width / initImage.Height; //原图与模版比例相等,直接缩放 if (templateRate == initRate) { //按模版大小生成最终图片 Image templateImage = new Bitmap(maxWidth, maxHeight); Graphics templateG = Graphics.FromImage(templateImage); templateG.InterpolationMode = InterpolationMode.High; templateG.SmoothingMode = SmoothingMode.HighQuality; templateG.Clear(Color.White); templateG.DrawImage(initImage, new Rectangle(0, 0, maxWidth, maxHeight), new Rectangle(0, 0, initImage.Width, initImage.Height), GraphicsUnit.Pixel); templateImage.Save(fileSaveUrl, initImage.RawFormat); } //原图与模版比例不等,裁剪后缩放 else { //裁剪对象 Image pickedImage; Graphics pickedG; //定位 Rectangle fromR = new Rectangle(0, 0, 0, 0); //原图裁剪定位 Rectangle toR = new Rectangle(0, 0, 0, 0); //目标定位 //宽为标准进行裁剪 if (templateRate > initRate) { //裁剪对象实例化 pickedImage = new Bitmap(initImage.Width, (int)Math.Floor(initImage.Width / templateRate)); pickedG = Graphics.FromImage(pickedImage); //裁剪源定位 fromR.X = 0; fromR.Y = (int)Math.Floor((initImage.Height - initImage.Width / templateRate) / 2); fromR.Width = initImage.Width; fromR.Height = (int)Math.Floor(initImage.Width / templateRate); //裁剪目标定位 toR.X = 0; toR.Y = 0; toR.Width = initImage.Width; toR.Height = (int)Math.Floor(initImage.Width / templateRate); } //高为标准进行裁剪 else { pickedImage = new Bitmap((int)Math.Floor(initImage.Height * templateRate), initImage.Height); pickedG = Graphics.FromImage(pickedImage); fromR.X = (int)Math.Floor((initImage.Width - initImage.Height * templateRate) / 2); fromR.Y = 0; fromR.Width = (int)Math.Floor(initImage.Height * templateRate); fromR.Height = initImage.Height; toR.X = 0; toR.Y = 0; toR.Width = (int)Math.Floor(initImage.Height * templateRate); toR.Height = initImage.Height; } //设置质量 pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = SmoothingMode.HighQuality; //裁剪 pickedG.DrawImage(initImage, toR, fromR, GraphicsUnit.Pixel); //按模版大小生成最终图片 using Image templateImage = new Bitmap(maxWidth, maxHeight); using Graphics templateG = Graphics.FromImage(templateImage); templateG.InterpolationMode = InterpolationMode.High; templateG.SmoothingMode = SmoothingMode.HighQuality; templateG.Clear(Color.White); templateG.DrawImage(pickedImage, new Rectangle(0, 0, maxWidth, maxHeight), new Rectangle(0, 0, pickedImage.Width, pickedImage.Height), GraphicsUnit.Pixel); //关键质量控制 //获取系统编码类型数组,包含了jpeg,bmpp,png,gif,tiff ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (var i in icis) { if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmpp" || i.MimeType == "image/png" || i.MimeType == "image/gif") { ici = i; } } EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(Encoder.Quality, quality); //保存缩略图 templateImage.Save(fileSaveUrl, ici, ep); pickedG.Dispose(); pickedImage.Dispose(); } } }
/// <summary> /// 正方型裁剪 /// 以图片中心为轴心,截取正方型,然后等比缩放 /// 用于头像处理 /// </summary> /// <param name="fromFile">原图Stream对象</param> /// <param name="fileSaveUrl">缩略图存放地址</param> /// <param name="side">指定的边长(正方型)</param> /// <param name="quality">质量(范围0-100)</param> public static void CutForSquare(this Stream fromFile, string fileSaveUrl, int side, int quality) { //创建目录 string dir = Path.GetDirectoryName(fileSaveUrl); Directory.CreateDirectory(dir); //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息) var initImage = Image.FromStream(fromFile, true); //原图宽高均小于模版,不作处理,直接保存 if ((initImage.Width <= side) && (initImage.Height <= side)) { initImage.Save(fileSaveUrl); } else { //原始图片的宽、高 int initWidth = initImage.Width; int initHeight = initImage.Height; //非正方型先裁剪为正方型 if (initWidth != initHeight) { //截图对象 Image pickedImage; Graphics pickedG; //宽大于高的横图 if (initWidth > initHeight) { //对象实例化 pickedImage = new Bitmap(initHeight, initHeight); pickedG = Graphics.FromImage(pickedImage); //设置质量 pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = 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, GraphicsUnit.Pixel); //重置宽 initWidth = initHeight; } //高大于宽的竖图 else { //对象实例化 pickedImage = new Bitmap(initWidth, initWidth); pickedG = Graphics.FromImage(pickedImage); //设置质量 pickedG.InterpolationMode = InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = 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, GraphicsUnit.Pixel); //重置高 initHeight = initWidth; } //将截图对象赋给原图 initImage = (Image)pickedImage.Clone(); //释放截图资源 initImage.Dispose(); pickedG.Dispose(); pickedImage.Dispose(); } //缩略图对象 using Image resultImage = new Bitmap(side, side); using var resultG = Graphics.FromImage(resultImage); //设置质量 resultG.InterpolationMode = InterpolationMode.HighQualityBicubic; resultG.SmoothingMode = SmoothingMode.HighQuality; //用指定背景色清空画布 resultG.Clear(Color.White); //绘制缩略图 resultG.DrawImage(initImage, new Rectangle(0, 0, side, side), new Rectangle(0, 0, initWidth, initHeight), GraphicsUnit.Pixel); //关键质量控制 //获取系统编码类型数组,包含了jpeg,bmpp,png,gif,tiff var icis = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (var i in icis) { if ((i.MimeType == "image/jpeg") || (i.MimeType == "image/bmpp") || (i.MimeType == "image/png") || (i.MimeType == "image/gif")) { ici = i; } } using var ep = new EncoderParameters(1) { Param = { [0] = new EncoderParameter(Encoder.Quality, quality) } }; //保存缩略图 resultImage.Save(fileSaveUrl, ici, ep); } }
/// <summary> /// 无损压缩图片 /// </summary> /// <param name="sFile">原图片</param> /// <param name="dFile">压缩后保存位置</param> /// <param name="dHeight">高度</param> /// <param name="dWidth"></param> /// <param name="flag">压缩质量 1-100</param> /// <returns></returns> public static bool GetPicThumbnail(string sFile, string dFile, ref string errMsg, int dHeight = 0, int dWidth = 0, int flag = 60) { System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile); ImageFormat tFormat = iSource.RawFormat; int sW = 0, sH = 0; //按比例缩放 Size tem_size = new Size(iSource.Width, iSource.Height); dHeight = dHeight == 0 ? tem_size.Height : dHeight; dWidth = dWidth == 0 ? tem_size.Width : dWidth; if (tem_size.Width > dHeight || tem_size.Width > dWidth) //将**改成c#中的或者操作符号 { if ((tem_size.Width * dHeight) > (tem_size.Height * dWidth)) { sW = dWidth; sH = (dWidth * tem_size.Height) / tem_size.Width; } else { sH = dHeight; sW = (tem_size.Width * dHeight) / tem_size.Height; } } else { sW = tem_size.Width; sH = tem_size.Height; } Bitmap ob = new Bitmap(dWidth, dHeight); Graphics g = Graphics.FromImage(ob); g.Clear(Color.WhiteSmoke); g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(iSource, new Rectangle((dWidth - sW) / 2, (dHeight - sH) / 2, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); g.Dispose(); //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) { ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径 } else { ob.Save(dFile, tFormat); } return(true); } catch (Exception ex) { errMsg = ex.Message + ",堆栈:" + ex.StackTrace + "InnerException:" + ex.InnerException; return(false); } finally { iSource.Dispose(); ob.Dispose(); } }
private void Convert(string filename, long compression_level) { try { Dispatcher.Invoke(new Action(() => { if (!File.Exists(log_path)) { using (File.Create(log_path)); } }), DispatcherPriority.ContextIdle); //string log_path = tb_browse.Text + "//log.txt"; //if (!File.Exists(log_path)) { // using (File.Create(log_path)) ; //} string destinaton = ""; string strTemp = System.IO.Path.GetExtension(filename).ToLower(); if (strTemp == ".tif") { destinaton = System.IO.Path.ChangeExtension(filename, "pdf"); } if (strTemp == ".tiff") { destinaton = System.IO.Path.ChangeExtension(filename, "pdf"); } System.Drawing.Image image = System.Drawing.Image.FromFile(filename); PdfDocument doc = new PdfDocument(); XGraphics xgr; int count = image.GetFrameCount(System.Drawing.Imaging.FrameDimension.Page); for (int pageNum = 0; pageNum < count; pageNum++) { image.SelectActiveFrame(System.Drawing.Imaging.FrameDimension.Page, pageNum); System.Drawing.Image image2; var ms = new MemoryStream(); var encoder = ImageCodecInfo.GetImageEncoders().First(c => c.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid); var encParams = new EncoderParameters() { Param = new[] { new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compression_level) } }; image.Save(ms, encoder, encParams); image2 = System.Drawing.Image.FromStream(ms); PdfPage page = new PdfPage(); doc.Pages.Add(page); xgr = XGraphics.FromPdfPage(page); // if (image2.Height == image2.Width) //return MyAspectEnum.Square; if (image2.Height > image2.Width) { page.Orientation = PdfSharp.PageOrientation.Portrait; } else { page.Orientation = PdfSharp.PageOrientation.Landscape; } XImage ximg = XImage.FromGdiPlusImage(image2); xgr.DrawImage(ximg, 0, 0); } doc.Save(destinaton); doc.Close(); image.Dispose(); // Dispatcher.Invoke(new Action(() => { rtb_log.AppendText("\nFile " + filename + " converted successfully!"); }), DispatcherPriority.ContextIdle); Dispatcher.Invoke(new Action(() => { rtb_log.AppendText("\nFile " + filename + " converted successfully!"); }), DispatcherPriority.ContextIdle); File.AppendAllText(log_path, Environment.NewLine + DateTime.Now.ToString() + " File " + filename + " converted successfully!"); label3.Content = "Files converted: " + counter + "/" + counter_total; counter++; } catch (Exception ex) { Dispatcher.Invoke(new Action(() => { rtb_log.AppendText("Error " + ex.Message); }), DispatcherPriority.ContextIdle); } }
private static void WriteLongLat(string fileIn, string fileOut, byte latDeg, byte latMin, double latSec, byte lonDeg, byte lonMin, double lonSec, bool isWest, bool isNorth) { const int length = 25; Encoder Enc = Encoder.Transformation; var EncParms = new EncoderParameters(1); ImageCodecInfo CodecInfo = GetEncoderInfo("image/jpeg"); // TODO: do not load the image to change again Image img = Image.FromFile(fileIn); PropertyItem[] PropertyItems = img.PropertyItems; int oldArrLength = PropertyItems.Length; var newProperties = new PropertyItem[oldArrLength]; img.PropertyItems.CopyTo(newProperties, 0); newProperties[0].Id = 0x0002; newProperties[0].Type = 5; //5-R 4-L 3-S newProperties[0].Len = length; newProperties[0].Value = new byte[length]; try { for (int i = 0; i < length; i++) { newProperties[0].Value[i] = 0; } } catch (Exception ex) { logger.InfoException("in WriteLongLat got an exception", ex); } //PropertyItems[0].Value = Pic.GetPropertyItem(4).Value; // bDescription; newProperties[0].Value[0] = latDeg; newProperties[0].Value[8] = latMin; byte secHelper = (byte)(latSec / 2.56); byte secRemains = (byte)((latSec - (secHelper * 2.56)) * 100); newProperties[0].Value[16] = secRemains; // add to the sum below x_x_*17_+16 newProperties[0].Value[17] = secHelper; // multiply by 2.56 newProperties[0].Value[20] = 100; img.SetPropertyItem(newProperties[0]); newProperties[1].Id = 0x0004; newProperties[1].Type = 5; //5-R 4-L 3-S newProperties[1].Len = length; newProperties[1].Value = new byte[length]; try { for (int i = 0; i < length; i++) { newProperties[1].Value[i] = 0; } } catch (Exception e) { Console.WriteLine("Error {0}", e); } newProperties[1].Value[0] = lonDeg; newProperties[1].Value[8] = lonMin; secHelper = (byte)(lonSec / 2.56); secRemains = (byte)((lonSec - (secHelper * 2.56)) * 100); newProperties[1].Value[16] = secRemains; // add to the sum bellow x_x_*17_+16 newProperties[1].Value[17] = secHelper; // multiply by 2.56 newProperties[1].Value[20] = 100; // multiply by 2.56 //PropertyItem current = Pic.GetPropertyItem(2); img.SetPropertyItem(newProperties[1]); //GPS Version newProperties[0].Id = 0x0000; newProperties[0].Type = 1; newProperties[0].Len = 4; newProperties[0].Value[0] = 2; newProperties[0].Value[1] = 2; newProperties[0].Value[2] = 0; newProperties[0].Value[3] = 0; img.SetPropertyItem(newProperties[0]); //GPS Lat REF newProperties[0].Id = 0x0001; newProperties[0].Type = 2; newProperties[0].Len = 2; if (isNorth) { newProperties[0].Value[0] = 78; //ASCII for N } else { newProperties[0].Value[0] = 83; //ASCII for S } newProperties[0].Value[1] = 0; img.SetPropertyItem(newProperties[0]); //GPS Lon REF newProperties[0].Id = 0x0003; newProperties[0].Type = 2; //5-R 4-L 3-S newProperties[0].Len = 2; if (isWest == false) { newProperties[0].Value[0] = 69; //ASCII for E } else { newProperties[0].Value[0] = 87; //ASCII for W } newProperties[0].Value[1] = 0; img.SetPropertyItem(newProperties[0]); // we cannot store in the same image, so use a temporary image instead string FilenameTemp = fileIn + ".temp"; // for lossless rewriting must rotate the image by 90 degrees! EncoderParameter EncParm = new EncoderParameter(Enc, (long)EncoderValue.TransformRotate90); EncParms.Param[0] = EncParm; // now write the rotated image with new description img.Save(FilenameTemp, CodecInfo, EncParms); // for computers with low memory and large pictures: release memory now img.Dispose(); img = null; GC.Collect(); // delete the original file, will be replaced later if (string.IsNullOrEmpty(fileOut)) { File.Delete(fileIn); } // now must rotate back the written picture img = Image.FromFile(FilenameTemp); EncParm = new EncoderParameter(Enc, (long)EncoderValue.TransformRotate270); EncParms.Param[0] = EncParm; if (string.IsNullOrEmpty(fileOut)) { img.Save(fileIn, CodecInfo, EncParms); } else { img.Save(fileOut, CodecInfo, EncParms); } // release memory now img.Dispose(); img = null; GC.Collect(); // delete the temporary picture File.Delete(FilenameTemp); }
internal static extern GpStatus GdipSaveAddImage(GpImage image, GpImage newImage, EncoderParameters encoderParams);
public override async Task Action() { CancelTokenSource = new CancellationTokenSource(); Progress("[图片裁剪器]开始处理..."); TaskSupervisor.Add(Task.Factory.StartNew(() => { try { while (!CancelTokenSource.IsCancellationRequested) { TaskSupervisor.DisposeInvalidTask(); if (CuttingSettingQueue.Count < 1) { Task.Delay(1000); continue; } CuttingSettingQueue.TryDequeue(out var waitProcessImg); if (!CancelTokenSource.IsCancellationRequested) { if (!TaskSupervisor.Add(new Task(new Action <object>(x => { if (!CancelTokenSource.IsCancellationRequested) { var cutterSetting = x as CutterSetting; if (!CancelTokenSource.IsCancellationRequested) { Progress($"[图片裁剪器]正在裁剪图片:{cutterSetting.ImgPath}"); var savePath = cutterSetting.SavePath; var imgExtensionName = Path.GetExtension(cutterSetting.ImgPath); if (string.IsNullOrEmpty(savePath)) { savePath = cutterSetting.ImgPath; } if (cutterSetting.ImgPath != savePath) { savePath = cutterSetting.ImgPath.Replace(cutterSetting.RootPath, savePath); } try { #region 裁剪 var cutImg = ImgHelper.CutImg(cutterSetting.ImgPath, cutterSetting.CutWidth, cutterSetting.CutHeight); #endregion #region 加水印 if (cutterSetting.IsSetWatermark) { switch (cutterSetting.WatermarkType) { case WatermarkTypeEnum.Image: try { var watermarkImg = Image.FromFile(cutterSetting.WatermarkTextOrPath); if (watermarkImg != null) { cutImg = Image.FromStream(WaterMarkHelper.AddWatermark(cutImg, imgExtensionName, watermarkImg, cutterSetting.WatermarkPosition)); } } catch (Exception ex) { Progress($"[图片裁剪器]发生异常:{ex}"); } break; case WatermarkTypeEnum.Text: cutImg = Image.FromStream(WaterMarkHelper.AddWatermark(cutImg, imgExtensionName, cutterSetting.WatermarkTextOrPath, Color.Black, cutterSetting.WatermarkPosition)); break; default: break; } } #endregion if (cutImg != null) { switch (imgExtensionName) { case ".jpg": ImageCodecInfo ici = ImgHelper.GetEncoderInfo("image/jpeg"); if (ici != null) { EncoderParameters ep = new EncoderParameters(1); ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100); cutImg.Save(savePath, ici, ep); ep.Dispose(); ep = null; ici = null; } else { cutImg.Save(savePath, ImageFormat.Jpeg); } break; case ".bmp": cutImg.Save(savePath, ImageFormat.Bmp); break; case ".gif": cutImg.Save(savePath, ImageFormat.Gif); break; case ".png": cutImg.Save(savePath, ImageFormat.Png); break; default: cutImg.Save(savePath, ImageFormat.Jpeg); break; } CutterProgress(TotalCount - CuttingSettingQueue.Count); } else { Progress($"[图片裁剪器][{cutterSetting.ImgPath}]裁剪时发生未知错误,未能实施裁剪"); CuttingSettingQueue.Enqueue(cutterSetting); } cutImg.Dispose(); } catch (Exception ex) { Progress($"[图片裁剪器]发生异常:{ex}"); } } } else { Thread.CurrentThread.Abort(); } }), waitProcessImg, CancelTokenSource.Token))) { CuttingSettingQueue.Enqueue(waitProcessImg); } } else { Thread.CurrentThread.Abort(); } TaskSupervisor.DisposeInvalidTask(); } } catch (Exception ex) { Progress($"[图片裁剪器]发生异常:{ex}"); } }, CancelTokenSource.Token)); }
internal static extern GpStatus GdipGetEncoderParameterList(GpImage image, ref Guid clsidEncoder, uint size, EncoderParameters buffer);
void SaveImage(Bitmap image) { fileCount = Directory.GetFiles(OutputFolder, "*.png", SearchOption.TopDirectoryOnly).Length; fileCount += Directory.GetFiles(OutputFolder, "*.jpg", SearchOption.TopDirectoryOnly).Length; string path; while (Directory.GetFiles(OutputFolder, GetScreenshotFileName() + ".*").Length > 0) { fileCount++; } //if we already have a screenshot of this name, increase index System.Drawing.Imaging.Encoder newEncoder = System.Drawing.Imaging.Encoder.Quality; ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); EncoderParameters encParams = new EncoderParameters(); EncoderParameter Quality; switch (ImageFileFormat) { case FILE_FORMAT_PNG: path = GetScreenshotFilePath() + ".png"; image.Save(path, ImageFormat.Png); break; case FILE_FORMAT_SMART: MemoryStream pngStream = new MemoryStream(); Quality = new EncoderParameter(newEncoder, 100L); encParams.Param[0] = Quality; image.Save(Application.LocalUserAppDataPath + @"\tempCapture.jpg", jpgEncoder, encParams); FileStream jpgStream = File.Open(Application.LocalUserAppDataPath + @"\tempCapture.jpg", FileMode.Open); image.Save(pngStream, ImageFormat.Png); if (pngStream.Length <= jpgStream.Length) { path = GetScreenshotFilePath() + ".png"; image.Save(path, ImageFormat.Png); } else { path = GetScreenshotFilePath() + ".jpg"; image.Save(path, jpgEncoder, encParams); } jpgStream.Dispose(); pngStream.Dispose(); try { File.Delete(Application.LocalUserAppDataPath + @"\tempCapture.jpg"); } catch { //don't tell mum } break; case FILE_FORMAT_JPG: Quality = new EncoderParameter(newEncoder, (int)trackBarJPGQuality.Value); encParams.Param[0] = Quality; path = GetScreenshotFilePath() + ".jpg"; image.Save(path, jpgEncoder, encParams); break; default: break; } encParams.Dispose(); Quality = null; jpgEncoder = null; newEncoder = null; }
///<summary> ///cmResize Ảnh theo chiều rộng được đưa ra ///cm thank to: http://webxaula.com/website/Thay-doi-kich-thuoc-anh-khi-upload-41-1.html ///</summary> public void ResizeImage(string ImageSavePath, string fileName, int MaxWidthSideSize, Stream Buffer) { int intNewWidth; int intNewHeight; System.Drawing.Image imgInput = System.Drawing.Image.FromStream(Buffer); ImageCodecInfo myImageCodecInfo; myImageCodecInfo = GetEncoderInfo("image/jpeg"); // System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter; //Giá trị width và height nguyên thủy của ảnh; int intOldWidth = imgInput.Width; int intOldHeight = imgInput.Height; //Kiểm tra xem ảnh ngang hay dọc; int intMaxSide; /*if (intOldWidth >= intOldHeight) { intMaxSide = intOldWidth; } else { intMaxSide = intOldHeight; }*/ //Để xác định xử lý ảnh theo width hay height thì bạn bỏ note phần trên; //Ở đây mình chỉ sử dụng theo width nên gán luôn intMaxSide= intOldWidth; ^^; intMaxSide = intOldWidth; if (intMaxSide > MaxWidthSideSize) { //Gán width và height mới. double dblCoef = MaxWidthSideSize / (double)intMaxSide; intNewWidth = Convert.ToInt32(dblCoef * intOldWidth); intNewHeight = Convert.ToInt32(dblCoef * intOldHeight); } else { //Nếu kích thước width/height (intMaxSide) cũ ảnh nhỏ hơn MaxWidthSideSize thì giữ nguyên //kích thước cũ; intNewWidth = intOldWidth; intNewHeight = intOldHeight; } //Tạo một ảnh bitmap mới; Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight); //Phần EncoderParameter cho phép bạn chỉnh chất lượng hình ảnh ở đây mình để chất lượng tốt //nhất là 100L; myEncoderParameter = new EncoderParameter(myEncoder, 100L); myEncoderParameters.Param[0] = myEncoderParameter; //Lưu ảnh; bmpResized.Save(ImageSavePath + fileName, myImageCodecInfo, myEncoderParameters); //Giải phóng tài nguyên; //Buffer.Close(); imgInput.Dispose(); bmpResized.Dispose(); }
//duplicate code! private void buttonTestScreenshot_Click(object sender, EventArgs e) { Bitmap img = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); string path = ""; using (Graphics buffer = Graphics.FromImage(img)) { buffer.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, img.Size, CopyPixelOperation.SourceCopy); System.Drawing.Imaging.Encoder newEncoder = System.Drawing.Imaging.Encoder.Quality; ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); EncoderParameters encParams = new EncoderParameters(); EncoderParameter Quality; if (checkBoxStampLogo.Checked) { ColorMatrix cm = new ColorMatrix(); cm.Matrix33 = 0.85f; ImageAttributes ia = new ImageAttributes(); ia.SetColorMatrix(cm); buffer.DrawImage(Properties.Resources.gm48Logo, new Rectangle(0, 0, 200, 200), 0, 0, 200, 200, GraphicsUnit.Pixel, ia); } MemoryStream ms = new MemoryStream(); try { File.Delete(path); } catch { //yeah... } switch (ImageFileFormat) { case FILE_FORMAT_PNG: path = Application.LocalUserAppDataPath + @"\testCapture.png"; img.Save(path, ImageFormat.Png); break; case FILE_FORMAT_SMART: MemoryStream pngStream = new MemoryStream(); path = Application.LocalUserAppDataPath + @"\testCapture"; Quality = new EncoderParameter(newEncoder, (int)trackBarJPGQuality.Value); encParams.Param[0] = Quality; img.Save(path + ".jpg", jpgEncoder, encParams); FileStream jpgStream = File.Open(path + ".jpg", FileMode.Open); img.Save(pngStream, ImageFormat.Png); if (pngStream.Length <= jpgStream.Length) { path = path + ".png"; img.Save(path, ImageFormat.Png); } else { path = path + ".jpg"; } jpgStream.Dispose(); pngStream.Dispose(); break; case FILE_FORMAT_JPG: Quality = new EncoderParameter(newEncoder, (int)trackBarJPGQuality.Value); encParams.Param[0] = Quality; path = Application.LocalUserAppDataPath + @"\testCapture.jpg"; img.Save(path, jpgEncoder, encParams); break; default: break; } Process.Start(path); img.Dispose(); } }
private void saveJpeg(string path, Bitmap img, long quality) { // Encoder parameter for image quality EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); // Jpeg image codec ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg"); if (jpegCodec == null) return; EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; img.Save(path, jpegCodec, encoderParams); }
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); }
public static void SaveJPG100(this Bitmap bmp, Stream stream) { var encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); bmp.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters); }
public static void CropImage(Image originalImage, string path, int _targetWidth, int _targetHeight, bool IsCrop, int imageType, Rectangle?destinationRectangle = null) { Bitmap _processedPhoto = null; Graphics grafik = null; int _lastWidth = 0, _lastHeight = 0; if (Array.IndexOf(originalImage.PropertyIdList, 274) > -1) { var orientation = (int)originalImage.GetPropertyItem(274).Value[0]; switch (orientation) { case 1: // No rotation required. break; case 2: originalImage.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case 3: originalImage.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 4: originalImage.RotateFlip(RotateFlipType.Rotate180FlipX); break; case 5: originalImage.RotateFlip(RotateFlipType.Rotate90FlipX); break; case 6: originalImage.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 7: originalImage.RotateFlip(RotateFlipType.Rotate270FlipX); break; case 8: originalImage.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } // This EXIF data is now invalid and should be removed. originalImage.RemovePropertyItem(274); } try { if ((originalImage.Width < _targetWidth) && (originalImage.Height < _targetHeight)) { _processedPhoto = new Bitmap(originalImage.Width, originalImage.Height); grafik = Graphics.FromImage(_processedPhoto); grafik.SmoothingMode = SmoothingMode.HighQuality; grafik.CompositingQuality = CompositingQuality.HighQuality; grafik.InterpolationMode = InterpolationMode.Default; grafik.PixelOffsetMode = PixelOffsetMode.HighQuality; var codec = ImageCodecInfo.GetImageEncoders(); var eParams = new EncoderParameters(1); eParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L); grafik.DrawImage(originalImage, 0, 0, originalImage.Width, originalImage.Height); _processedPhoto.Save(path, codec[imageType], eParams); GC.Collect(); } else { if (IsCrop != true) { float _OrjiRatio = (float)originalImage.Width / (float)originalImage.Height; float _hedefRatio = (float)_targetWidth / (float)_targetHeight; if (_OrjiRatio > _hedefRatio) //Widthe Göre { _lastWidth = _targetWidth; _lastHeight = Convert.ToInt32(_targetWidth / _OrjiRatio); } else //heighte göre { _lastHeight = _targetHeight; _lastWidth = Convert.ToInt32(_targetHeight * _OrjiRatio); } _processedPhoto = new Bitmap(_lastWidth, _lastHeight); grafik = Graphics.FromImage(_processedPhoto); grafik.SmoothingMode = SmoothingMode.HighQuality; grafik.CompositingQuality = CompositingQuality.HighQuality; grafik.InterpolationMode = InterpolationMode.Default; grafik.PixelOffsetMode = PixelOffsetMode.HighQuality; var codec = ImageCodecInfo.GetImageEncoders(); var eParams = new EncoderParameters(1); eParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L); grafik.DrawImage(originalImage, 0, 0, _lastWidth, _lastHeight); _processedPhoto.Save(path, codec[imageType], eParams); GC.Collect(); } else { float _OrjiRatio = (float)originalImage.Width / (float)originalImage.Height; float _hedefRatio = (float)_targetWidth / (float)_targetHeight; if (_hedefRatio < _OrjiRatio) // heighte göre { _lastHeight = _targetHeight; _lastWidth = Convert.ToInt32(_targetHeight * _OrjiRatio); } else // widthe göre { _lastWidth = _targetWidth; _lastHeight = Convert.ToInt32(_targetWidth / _OrjiRatio); } _processedPhoto = new Bitmap(_lastWidth, _lastHeight); grafik = Graphics.FromImage(_processedPhoto); grafik.SmoothingMode = SmoothingMode.HighQuality; grafik.CompositingQuality = CompositingQuality.HighQuality; grafik.InterpolationMode = InterpolationMode.Default; grafik.PixelOffsetMode = PixelOffsetMode.HighQuality; var codec = ImageCodecInfo.GetImageEncoders(); var eParams = new EncoderParameters(1); eParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L); grafik.DrawImage(originalImage, 0, 0, _lastWidth, _lastHeight); GC.Collect(); var _processedPhotoWidth = _processedPhoto.Width; var _processedPhotoHeight = _processedPhoto.Height; var _ortWidth = Convert.ToInt32((_processedPhoto.Width - _targetWidth) / 2); var _ortHeight = Convert.ToInt32((_processedPhoto.Height - _targetHeight) / 2); var sourceRectangle = new Rectangle(_ortWidth, _ortHeight, _targetWidth, _targetHeight); if (destinationRectangle == null) { destinationRectangle = new Rectangle(Point.Empty, sourceRectangle.Size); } var croppedImage = new Bitmap(destinationRectangle.Value.Width, destinationRectangle.Value.Height); using (var graphics = Graphics.FromImage(croppedImage)) { graphics.DrawImage(_processedPhoto, destinationRectangle.Value, sourceRectangle, GraphicsUnit.Pixel); } croppedImage.Save(path, codec[imageType], eParams); GC.Collect(); } } } catch (Exception) { throw; } }
protected void Page_Load(object sender, EventArgs e) { //try { picID = yeyRequest.Params("fileid"); HttpPostedFile file = Request.Files["txtshareF"]; //如果读取不到文件对象 if (file == null) { if (!String.IsNullOrEmpty(Request["picID"])) { Response.Clear(); Response.Write("上传失败!"); Response.End(); } } else { picID = Request["picID"]; //获取文件夹路径 string path = Server.MapPath("~" + SaveFilePath); //网站中有一个 uploadedFiles 文件夹,存储上传来的图片 //生成文件名(系统要重新生成一个文件名,但注意扩展名要相同。千万不要用中文名称!!!) string originalFileName = file.FileName; string fileExtension = originalFileName.Substring(originalFileName.LastIndexOf('.'), originalFileName.Length - originalFileName.LastIndexOf('.')); string currentFileName = picID + fileExtension; //例如:可使用“随机数+扩展名”生成文件名 //生成文件路径 string imageUrl = path + currentFileName; //保存文件 file.SaveAs(imageUrl); using (System.Drawing.Image image = System.Drawing.Image.FromFile(imageUrl)) { int width = image.Width; int height = image.Height; int picWidth = 0; int picHeight = 0; if (width >= height) { picWidth = 400; picHeight = Convert.ToInt32(((400 * 1.0 / width) * height)); } else { picHeight = 400; picWidth = Convert.ToInt32(((400 * 1.0 / height) * width)); } Image ImageUpload = Image.FromStream(file.InputStream, true, true); ImageFormat imageFormat = ImageUpload.RawFormat; Image imageFile = resizeImage(ImageUpload, new Size { Height = picHeight, Width = picWidth }); string newFileName = picID + "resize" + fileExtension; ImageCodecInfo[] icis = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; //foreach (ImageCodecInfo i in icis) //{ // if (i.MimeType == "image/jpeg" || i.MimeType == "image/jpg" || 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)100); if (fileExtension.ToLower().IndexOf("jpg") > -1 || fileExtension.ToLower().IndexOf("jpeg") > -1) { imageFile.Save(path + newFileName, icis[1], ep); } else if (fileExtension.IndexOf("png") > -1) { imageFile.Save(path + newFileName, System.Drawing.Imaging.ImageFormat.Png); } else { imageFile.Save(path + newFileName); } file.InputStream.Close(); imageFile.Dispose(); image.Dispose(); string url = Request.Url.GetLeftPart(UriPartial.Authority) + SaveFilePath + newFileName; Response.Clear(); Response.Write(url + "," + picWidth.ToString() + "," + picHeight.ToString()); } //HttpContext.Current.ApplicationInstance.CompleteRequest(); Response.End(); //-----------------获取文件url----------------- //获取img的url地址(如果 file.FileName 有汉字,要进行url编码) //string url = Request.Url.GetLeftPart(UriPartial.Authority) + "/uploadedFiles/" + currentFileName; //此时 result 已被赋值为“<iframe src="http://localhost:8080/wangEditor_uploadImg_assist.html#ok|图片url地址"></iframe>” } //} //catch (Exception ex) //{ // Log.LogError(ex.Message, ex); // Response.End(); //} //finally //{ //} }
private void SaveImage(System.Drawing.Image image, string suffix) { // store the resolution in output file. // Call this method after actual draw because it may affect drawing the text if (image is Bitmap) { (image as Bitmap).SetResolution(ResolutionX, ResolutionY); } if (IsMultiFrameTiff) { // select the image encoder ImageCodecInfo info = ExportUtils.GetCodec("image/tiff"); EncoderParameters ep = new EncoderParameters(2); ep.Param[0] = new EncoderParameter(Encoder.Compression, MonochromeTiff ? (long)MonochromeTiffCompression : (long)EncoderValue.CompressionLZW); if (image == masterTiffImage) { // save the master bitmap if (MonochromeTiff) { masterTiffImage = ConvertToBitonal(image as Bitmap); } ep.Param[1] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.MultiFrame); masterTiffImage.Save(Stream, info, ep); } else { // save the frame if (MonochromeTiff) { System.Drawing.Image oldImage = image; image = ConvertToBitonal(image as Bitmap); oldImage.Dispose(); } ep.Param[1] = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.FrameDimensionPage); masterTiffImage.SaveAdd(image, ep); } } else if (ImageFormat != ImageExportFormat.Metafile) { string extension = Path.GetExtension(FileName); string fileName = Path.ChangeExtension(FileName, suffix + extension); // empty suffix means that we should use the Stream that was created in the ExportBase Stream stream = suffix == "" ? Stream : new FileStream(fileName, FileMode.Create); if (suffix != "") { GeneratedFiles.Add(fileName); } if (ImageFormat == ImageExportFormat.Jpeg) { ExportUtils.SaveJpeg(image, stream, JpegQuality); } else if (ImageFormat == ImageExportFormat.Tiff && MonochromeTiff) { // handle monochrome tiff separately ImageCodecInfo info = ExportUtils.GetCodec("image/tiff"); EncoderParameters ep = new EncoderParameters(); ep.Param[0] = new EncoderParameter(Encoder.Compression, (long)MonochromeTiffCompression); using (Bitmap bwImage = ConvertToBitonal(image as Bitmap)) { bwImage.Save(stream, info, ep); } } else { ImageFormat format = System.Drawing.Imaging.ImageFormat.Bmp; switch (ImageFormat) { case ImageExportFormat.Gif: format = System.Drawing.Imaging.ImageFormat.Gif; break; case ImageExportFormat.Png: format = System.Drawing.Imaging.ImageFormat.Png; break; case ImageExportFormat.Tiff: format = System.Drawing.Imaging.ImageFormat.Tiff; break; } image.Save(stream, format); } if (suffix != "") { stream.Dispose(); } } if (image != masterTiffImage) { image.Dispose(); } }
/// <summary> /// /// </summary> /// <param name="width"></param> /// <returns></returns> public override string ThumbnailWithRatio(int width) { string serverPath = Dir.GetUpFilePathWithSystem(FileName); if (serverPath.IsNull()) { return(""); } FileInfo fileInfo = new FileInfo(serverPath); if (!fileInfo.Exists) { return(""); } string ext = fileInfo.Extension.ToLower(); if (!EXTS.Contains(ext)) { return(""); } try { using var image = Image.FromFile(serverPath); if (image.IsNull()) { return(""); } if (image.Width == 0) { return(""); } if (width >= image.Width) { return(""); } float ratio = (float)width / (float)image.Width; float height = ratio * image.Height; using var newImage = new Bitmap((int)width, (int)height); using var gra = Graphics.FromImage(newImage); gra.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; gra.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; gra.DrawImage(image, 0, 0, newImage.Width, newImage.Height); var codeInfo = FindImageCodecInfo(); string filename = Path.Combine(Dir.GetUpFileDirWithSystem(), $"thumbnail_{fileInfo.Name}"); if (codeInfo.IsNull()) { newImage.Save(filename); } else { using var param = new EncoderParameters(1); param.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)80); newImage.Save(filename, codeInfo, param); } return($"thumbnail_{fileInfo.Name}"); } catch { return(""); } }
internal PageImage GetPageImage(Report rpt, Row row) { string mtype = null; Stream strm = null; System.Drawing.Bitmap im = null; PageImage pi = null; WorkClass wc = GetWC(rpt); if (wc.PgImage != null) { // have we already generated this one // reuse most of the work; only position will likely change pi = new PageImage(wc.PgImage.ImgFormat, wc.PgImage.ImageData, wc.PgImage.SamplesW, wc.PgImage.SamplesH); pi.Name = wc.PgImage.Name; // this is name it will be shared under return(pi); } try { strm = GetImageStream(rpt, row, out mtype); if (strm == null) { rpt.rl.LogError(4, string.Format("Unable to load image {0}.", this._Value == null?"": this._Value.EvaluateString(rpt, row))); return(null); } im = Bitmap.FromStream(strm); int height = im.Height; int width = im.Width; MemoryStream ostrm = new MemoryStream(); ImageFormat imf; // if (mtype.ToLower() == "image/jpeg") //TODO: how do we get png to work // imf = ImageFormatType.Jpeg; // else imf = ImageFormat.Jpeg; System.Drawing.Imaging.ImageCodecInfo[] info; info = ImageCodecInfo.GetImageEncoders(); EncoderParameters encoderParameters; encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImageQualityManager.EmbeddedImageQuality); System.Drawing.Imaging.ImageCodecInfo codec = null; for (int i = 0; i < info.Length; i++) { if (info[i].FormatDescription == "JPEG") { codec = info[i]; break; } } im.Save(ostrm, codec, encoderParameters); byte[] ba = ostrm.ToArray(); ostrm.Close(); pi = new PageImage(imf, ba, width, height); pi.SI = new StyleInfo(); // this will just default everything if (_BackgroundRepeat != null) { string r = _BackgroundRepeat.EvaluateString(rpt, row).ToLower(); switch (r) { case "repeat": pi.Repeat = ImageRepeat.Repeat; break; case "repeatx": pi.Repeat = ImageRepeat.RepeatX; break; case "repeaty": pi.Repeat = ImageRepeat.RepeatY; break; case "norepeat": default: pi.Repeat = ImageRepeat.NoRepeat; break; } } else { pi.Repeat = ImageRepeat.Repeat; } if (_ConstantImage) { wc.PgImage = pi; // create unique name; PDF generation uses this to optimize the saving of the image only once pi.Name = "pi" + Interlocked.Increment(ref Parser.Counter).ToString(); // create unique name } } finally { if (strm != null) { strm.Close(); } if (im != null) { im.Dispose(); } } return(pi); }
// Saves the image to specific location, save location includes filename private static void saveImageToLocation(Image theImage, string saveLocation) { // Strip the file from the end of the dir string saveFolder = Path.GetDirectoryName(saveLocation); if (!Directory.Exists(saveFolder)) { Directory.CreateDirectory(saveFolder); } ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg); // Create an Encoder object based on the GUID // for the Quality parameter category. System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; // Create an EncoderParameters object. // An EncoderParameters object has an array of EncoderParameter // objects. In this case, there is only one // EncoderParameter object in the array. EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 90L); myEncoderParameters.Param[0] = myEncoderParameter; // Save to disk theImage.Save(saveLocation, jgpEncoder, myEncoderParameters); }
/// <summary> /// Saves the current image to the specified file path. /// </summary> /// <param name="filePath">The path to save the image to.</param> /// <returns> /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class. /// </returns> public ImageFactory Save(string filePath) { if (this.ShouldProcess) { // We need to check here if the path has an extension and remove it if so. // This is so we can add the correct image format. int length = filePath.LastIndexOf(".", StringComparison.Ordinal); string extension = this.ImageFormat.GetFileExtension(this.OriginalExtension); if (!string.IsNullOrWhiteSpace(extension)) { filePath = length == -1 ? filePath + extension : filePath.Substring(0, length) + extension; } // Fix the colour palette of indexed images. this.FixIndexedPallete(); // ReSharper disable once AssignNullToNotNullAttribute DirectoryInfo directoryInfo = new DirectoryInfo(Path.GetDirectoryName(filePath)); if (this.ImageFormat.Equals(ImageFormat.Jpeg)) { // Jpegs can be saved with different settings to include a quality setting for the JPEG compression. // This improves output compression and quality. using (EncoderParameters encoderParameters = ImageUtils.GetEncodingParameters(this.JpegQuality)) { ImageCodecInfo imageCodecInfo = ImageCodecInfo.GetImageEncoders() .FirstOrDefault(ici => ici.MimeType.Equals(this.MimeType, StringComparison.OrdinalIgnoreCase)); if (imageCodecInfo != null) { for (int i = 0; i < 3; i++) { try { if (!directoryInfo.Exists) { directoryInfo.Create(); } this.Image.Save(filePath, imageCodecInfo, encoderParameters); break; } catch (Exception) { Thread.Sleep(200); } } } } } else { for (int i = 0; i < 3; i++) { try { if (!directoryInfo.Exists) { directoryInfo.Create(); } this.Image.Save(filePath, this.ImageFormat); break; } catch (Exception) { Thread.Sleep(200); } } } } return(this); }
public ActionResult Upload(HttpPostedFileBase file) { // check if a file uploads if( file != null && file.ContentLength > 0) { // generate a new file id string n = Guid.NewGuid().ToString("D"); //generate filepath var filePath = Server.MapPath("~/App_Data/uploads/" + n); //here all image file extensions are stored with ',' seperator in app-key-value web.config file //ConfigManager.Image class extracts value from web.config file and stores in an array var imageFormats = ConfigManager.Image.CompressImageFormats; //check for image types if (imageFormats.Contains(Path.GetExtension(file.FileName))) { //convert HttpPostedFileBase file to image var image = Image.FromStream(file.InputStream, true, true); //resize image var bitmap = ResizeImage(image); //optional step - save all images as jpg for uniformity ImageCodecInfo jpgInfo = ImageCodecInfo.GetImageEncoders() .Where(codecInfo => codecInfo.MimeType == "image/jpeg").First(); //set the quality of output image here range [0..100] var quality = 10; using (EncoderParameters encParams = new EncoderParameters(1)) { encParams.Param[0] = new EncoderParameter(Encoder.Quality, (long)quality); //save bitmap bitmap.Save(filePath, jpgInfo, encParams); // return the details of the file return Json(new { id = n, name = file.FileName.Split('.').FirstOrDefault()+"."+"jpg", type = "jpg" }); } } //if here input file is not image // save the file file.SaveAs(filePath); // return the details of the file return Json(new { id = n, name = file.FileName, type = file.FileName.Split('.').Reverse().FirstOrDefault() }); } // if here, return nothing return Json(new { name = "", id = "", type = "" }); }
/// <summary> /// 图片水印 /// </summary> /// <param name="imgPath">服务器图片相对路径</param> /// <param name="filename">保存文件名</param> /// <param name="watermarkFilename">水印文件相对路径</param> /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param> /// <param name="quality">附加水印图片质量,0-100</param> /// <param name="watermarkTransparency">水印的透明度 1--10 10为不透明</param> public static void AddImageSignPic(string imgPath, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency) { if (!File.Exists(Utils.GetMapPath(imgPath))) { return; } byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath)); Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes)); filename = Utils.GetMapPath(filename); if (watermarkFilename.StartsWith("/") == false) { watermarkFilename = "/" + watermarkFilename; } watermarkFilename = Utils.GetMapPath(watermarkFilename); if (!File.Exists(watermarkFilename)) { return; } Graphics g = Graphics.FromImage(img); //设置高质量插值法 g.InterpolationMode = InterpolationMode.HighQualityBicubic; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.AntiAlias; g.PixelOffsetMode = PixelOffsetMode.HighQuality; Image watermark = new Bitmap(watermarkFilename); if (watermark.Height >= img.Height || watermark.Width >= img.Width) { return; } ImageAttributes imageAttributes = new ImageAttributes(); ColorMap colorMap = new ColorMap { OldColor = Color.FromArgb(255, 0, 255, 0), NewColor = Color.FromArgb(0, 0, 0, 0) }; ColorMap[] remapTable = { colorMap }; imageAttributes.SetRemapTable(remapTable, ColorAdjustType.Bitmap); float transparency = 0.5F; if (watermarkTransparency >= 1 && watermarkTransparency <= 10) { transparency = (watermarkTransparency / 10.0F); } 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, transparency, 0.0f }, new float[] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }; ColorMatrix colorMatrix = new ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(colorMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap); int xpos = 0; int ypos = 0; switch (watermarkStatus) { case 1: xpos = (int)(img.Width * (float).01); ypos = (int)(img.Height * (float).01); break; case 2: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)(img.Height * (float).01); break; case 3: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)(img.Height * (float).01); break; case 4: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 5: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 6: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)((img.Height * (float).50) - (watermark.Height / 2)); break; case 7: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).99) - watermark.Height); break; case 8: xpos = (int)((img.Width * (float).50) - (watermark.Width / 2)); ypos = (int)((img.Height * (float).99) - watermark.Height); break; case 9: xpos = (int)((img.Width * (float).99) - (watermark.Width)); ypos = (int)((img.Height * (float).99) - watermark.Height); break; } g.DrawImage(watermark, new Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, GraphicsUnit.Pixel, imageAttributes); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) { ici = codec; } } EncoderParameters encoderParams = new EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) { quality = 80; } qualityParam[0] = quality; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) { img.Save(filename, ici, encoderParams); } else { img.Save(filename); } g.Dispose(); img.Dispose(); watermark.Dispose(); imageAttributes.Dispose(); }
internal static extern GpStatus GdipSaveImageToFile(GpImage image, string filename, ref Guid clsidEncoder, EncoderParameters encoderParams);
/// <summary> /// 文字水印 /// </summary> /// <param name="imgPath">服务器图片相对路径</param> /// <param name="filename">保存文件名</param> /// <param name="watermarkText">水印文字</param> /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param> /// <param name="quality">附加水印图片质量,0-100</param> /// <param name="fontname">字体</param> /// <param name="fontsize">字体大小</param> public static void AddImageSignText(string imgPath, string filename, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize) { byte[] _ImageBytes = File.ReadAllBytes(Utils.GetMapPath(imgPath)); Image img = Image.FromStream(new System.IO.MemoryStream(_ImageBytes)); filename = Utils.GetMapPath(filename); Graphics g = Graphics.FromImage(img); //设置高质量插值法 g.InterpolationMode = InterpolationMode.HighQualityBicubic; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.AntiAlias; g.PixelOffsetMode = PixelOffsetMode.HighQuality; Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel); var crSize = g.MeasureString(watermarkText, drawFont); float xpos = 0; float ypos = 0; switch (watermarkStatus) { case 1: xpos = img.Width * (float).01; ypos = img.Height * (float).01; break; case 2: xpos = (img.Width * (float).50) - (crSize.Width / 2); ypos = img.Height * (float).01; break; case 3: xpos = (img.Width * (float).99) - crSize.Width; ypos = img.Height * (float).01; break; case 4: xpos = img.Width * (float).01; ypos = (img.Height * (float).50) - (crSize.Height / 2); break; case 5: xpos = (img.Width * (float).50) - (crSize.Width / 2); ypos = (img.Height * (float).50) - (crSize.Height / 2); break; case 6: xpos = (img.Width * (float).99) - crSize.Width; ypos = (img.Height * (float).50) - (crSize.Height / 2); break; case 7: xpos = img.Width * (float).01; ypos = (img.Height * (float).99) - crSize.Height; break; case 8: xpos = (img.Width * (float).50) - (crSize.Width / 2); ypos = (img.Height * (float).99) - crSize.Height; break; case 9: xpos = (img.Width * (float).99) - crSize.Width; ypos = (img.Height * (float).99) - crSize.Height; break; } g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1); g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) { ici = codec; } } EncoderParameters encoderParams = new EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) { quality = 80; } qualityParam[0] = quality; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) { img.Save(filename, ici, encoderParams); } else { img.Save(filename); } g.Dispose(); img.Dispose(); }
static void SaveImage(Image img, Stream outputStream, ImageFormat fmt) { if (fmt==ImageFormat.Jpeg) { // for jpeg, lets set 90% quality explicitely ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); var jpegCodec = codecs.Where( c=> c.FormatID == ImageFormat.Jpeg.Guid ).FirstOrDefault(); if (jpegCodec!=null) { var jpegEncoderParameters = new EncoderParameters(1); jpegEncoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L); img.Save(outputStream, jpegCodec, jpegEncoderParameters); return; } } img.Save(outputStream, fmt); }
/// <summary> /// Thumbnail image /// </summary> /// <param name="info">NBrightInfo class of PRD type</param> /// <param name="width">width</param> /// <param name="height">height</param> /// <param name="idx">index of the image to display</param> /// <param name="attributes">free text added onto end of url parameters</param> /// <returns>Thumbnailer url</returns> public IEncodedString ProductImage(NBrightInfo info, string width = "150", string height = "0", string idx = "1", string attributes = "", bool fileImage = false, bool outputPNG = false) { var url = ""; var imageurlsrc = info.GetXmlProperty("genxml/imgs/genxml[" + idx + "]/hidden/imageurl"); if (fileImage) { var src = HttpContext.Current.Server.MapPath(imageurlsrc); var strCacheKey = info.PortalId + "*" + src + "*" + Utils.GetCurrentCulture() + "*imgfile:" + width + "*" + height + "*"; url = (String)Utils.GetCache(strCacheKey); if (String.IsNullOrEmpty(url)) { var imgpath = Path.GetFileNameWithoutExtension(src); var ext = ".jpg"; if (outputPNG) { ext = ".png"; } var thumbname = imgpath + "_Thumb" + width + "x" + height + ext; imgpath = Path.GetFullPath(src).Replace(Path.GetFileName(src), "") + thumbname; url = imageurlsrc.Replace(Path.GetFileName(src), thumbname); if (!File.Exists(imgpath)) { var newImage = ImgUtils.CreateThumbnail(src, Convert.ToInt32(width), Convert.ToInt32(height)); ImageCodecInfo useEncoder; useEncoder = ImgUtils.GetEncoder(ImageFormat.Jpeg); if (outputPNG) { useEncoder = ImgUtils.GetEncoder(ImageFormat.Png); } var encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L); try { newImage.Save(imgpath, useEncoder, encoderParameters); } catch (Exception exc) { if (StoreSettings.Current.DebugMode) { url = exc.ToString(); } } } if (!StoreSettings.Current.DebugMode) { Utils.SetCache(strCacheKey, url); } } } else { url = StoreSettings.NBrightBuyPath() + "/NBrightThumb.ashx?src=" + imageurlsrc + "&w=" + width + "&h=" + height + attributes; } return(new RawString(url)); }
// 檔案存檔 protected void bn_upfile_ok_Click(object sender, EventArgs e) { double fCnt = 1.0; int ac_size = 0, ac_width = 0, ac_height = 0, s_width = 0, s_height = 0; string SqlString = "", mErr = ""; string ac_name = "", ac_ext = "", ac_desc = "", ac_type = ""; string file_ext = ".jpg.gif.png.bmp.wmf"; // 允許上傳的檔案副檔名 #region 儲存檔案 if (fu_upfile.HasFile) { // 處理上傳檔案,說明及檔案內容存入資料庫 using (SqlConnection Sql_Conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["AppSysConnectionString"].ConnectionString)) { Sql_Conn.Open(); using (SqlCommand Sql_Command = new SqlCommand()) { MemoryStream ms_tmp = new MemoryStream(); ac_name = fu_upfile.FileName; ac_ext = Path.GetExtension(ac_name).ToString().ToLower(); if (file_ext.Contains(ac_ext)) { ac_size = fu_upfile.PostedFile.ContentLength; ac_type = fu_upfile.PostedFile.ContentType; ac_desc = tb_ac_desc.Text.Trim(); #region 取得圖型資料及縮圖處理 // FileUpload 的檔案內容存入 Image using (System.Drawing.Image img_tmp = System.Drawing.Image.FromStream(fu_upfile.PostedFile.InputStream, true)) { ac_height = img_tmp.Height; // 實際高度 ac_width = img_tmp.Width; // 實際寬度 // 維持圖檔比例的方式,計算與縮圖 120 * 120 的比例 if (ac_width > ac_height) fCnt = ac_width / 120.0; else fCnt = ac_height / 120.0; // 實際圖比縮圖大時才要處理,否則仍為原圖檔尺寸 if (fCnt > 1) { s_width = (int)(ac_width / fCnt); // 縮圖寬度 s_height = (int)(ac_height / fCnt); // 縮圖高度 } else { s_width = ac_width; // 縮圖寬度 s_height = ac_height; // 縮圖高度 } #region 呼叫 Bitmap 物件的 GetThumbnailImage 方法來建立一個縮圖 using (System.Drawing.Image img_thumb = img_tmp.GetThumbnailImage(s_width, s_height, new System.Drawing.Image.GetThumbnailImageAbort(img_Abort), IntPtr.Zero)) { // 縮圖的壓縮比為 75% EncoderParameters eps = new EncoderParameters(); eps.Param[0] = new EncoderParameter(Encoder.Quality, (long)75); img_thumb.Save(ms_tmp, GetEncoderInfo("image/jpeg"), eps); // 以預設壓縮比儲存 jpeg (75%) // img_thumb.Save(ms_tmp, ImageFormat.Jpeg); } #endregion } #endregion #region 檔案存入資料庫 SqlString = "Insert Into Al_Content (al_sid, ac_name, ac_ext, ac_size, ac_type, ac_desc"; SqlString = SqlString + " , ac_content, ac_width, ac_height, ac_thumb)"; SqlString = SqlString + " Values (@al_sid, @ac_name, @ac_ext, @ac_size, @ac_type, @ac_desc"; SqlString = SqlString + " , @ac_content, @ac_width, @ac_height, @ac_thumb)"; Sql_Command.CommandText = SqlString; Sql_Command.Connection = Sql_Conn; Sql_Command.Parameters.AddWithValue("al_sid", lb_al_sid.Text); Sql_Command.Parameters.AddWithValue("ac_name", ac_name); Sql_Command.Parameters.AddWithValue("ac_ext", ac_ext); Sql_Command.Parameters.AddWithValue("ac_size", ac_size); Sql_Command.Parameters.AddWithValue("ac_type", ac_type); Sql_Command.Parameters.AddWithValue("ac_desc", ac_desc); Sql_Command.Parameters.AddWithValue("ac_content", fu_upfile.FileBytes); Sql_Command.Parameters.AddWithValue("ac_width", ac_width); Sql_Command.Parameters.AddWithValue("ac_height", ac_height); Sql_Command.Parameters.AddWithValue("ac_thumb", ms_tmp.ToArray()); Sql_Command.ExecuteNonQuery(); ms_tmp.Close(); ms_tmp.Dispose(); //預設上傳檔案大小為 4096KB, 執行時間 120秒, 如要修改,要到 Web.Config 處修改下列數據 //<system.web> //<httpRuntime maxRequestLength="4096" executionTimeout="120"/> //</system.web> #endregion } else mErr = "不接受「" + ac_name + "」的檔案格式!\\n(僅接受「" + file_ext + "」等格式)\\n"; } } } else mErr = "沒有選擇任何上傳的檔案!\\n"; #endregion if (mErr == "") lt_show.Text = "<script language=\"javascript\">alert(\"檔案上傳完成!\\n\");parent.close_all();parent.thumb_reload();</script>"; else lt_show.Text = "<script language=\"javascript\">alert(\"" + mErr + "\");parent.close_all();parent.clean_win();</script>"; }
/// <summary> /// 正方型裁剪 /// 以图片中心为轴心,截取正方型,然后等比缩放 /// 用于头像处理 /// </summary> /// <remarks></remarks> /// <param name="fromFile">原图Stream对象</param> /// <param name="fileSaveUrl">缩略图存放地址</param> /// <param name="side">指定的边长(正方型)</param> /// <param name="quality">质量(范围0-100)</param> public static void CutForSquare(System.IO.Stream fromFile, 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.FromStream(fromFile, 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(); } }
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; }
private static int ChangePhotoTime(IEnumerable <FileInfo> fileInfos, int seconds) { int count = 0; Image dummyImage = new Bitmap(Environment.CurrentDirectory + "/dummy.jpg"); var dummyTime = dummyImage.GetPropertyItem(0x0132); foreach (var fileInfo in fileInfos) { var extName = Path.GetExtension(fileInfo.Name).ToUpper(); if ((extName != ".JPG" && extName != ".JPEG") || fileInfo.Name == "dummy.jpg" || fileInfo.Name.Contains("_Done")) { continue; } Bitmap image = new Bitmap(fileInfo.FullName); DateTime photoDate; //从文件名中获取时间 if (seconds == 0) { var fNameFrags = fileInfo.Name.Split('_'); int year = 2000 + int.Parse(fNameFrags[1].Substring(0, 4)); int month = int.Parse(fNameFrags[1].Substring(4, 2)); int day = int.Parse(fNameFrags[1].Substring(6, 2)); int hour = int.Parse(fNameFrags[2].Substring(0, 2)); int minute = int.Parse(fNameFrags[2].Substring(2, 2)); int second = int.Parse(fNameFrags[2].Substring(4, 2)); photoDate = new DateTime(year, month, day, hour, minute, second); var newTimeString = photoDate.ToString("yyyy:MM:dd HH:mm:ss"); newTimeString += "\0"; dummyTime.Value = Encoding.ASCII.GetBytes(newTimeString); dummyTime.Len = dummyTime.Value.Length; image.SetPropertyItem(dummyTime); } else { var originTime = image.GetPropertyItem(0x0132); var timeString = Encoding.ASCII.GetString(originTime.Value); timeString = timeString.Replace(" ", ":"); var timeFrags = timeString.Split(':'); int year = int.Parse(timeFrags[0]); int month = int.Parse(timeFrags[1]); int day = int.Parse(timeFrags[2]); int hour = int.Parse(timeFrags[3]); int minute = int.Parse(timeFrags[4]); int second = int.Parse(timeFrags[5]); photoDate = new DateTime(year, month, day, hour, minute, second); photoDate = photoDate.AddSeconds(seconds); var newTimeString = photoDate.ToString("yyyy:MM:dd HH:mm:ss"); newTimeString += "\0"; originTime.Value = Encoding.ASCII.GetBytes(newTimeString); originTime.Len = originTime.Value.Length; image.SetPropertyItem(originTime); } EncoderParameters encoderParameters = new EncoderParameters(1); var myEncoder = System.Drawing.Imaging.Encoder.Quality; encoderParameters.Param[0] = new EncoderParameter(myEncoder, 100L); var myImageCodecInfo = GetEncoderInfo("image/jpeg"); var newFileName = Path.GetFileNameWithoutExtension(fileInfo.Name) + "_Done" + extName; image.Save(newFileName, myImageCodecInfo, encoderParameters); image.Dispose(); count++; } return(count); }
public void SaveFrame(Bitmap e, int quality) { try { foreach (ImageCodecInfo ici in ImageCodecInfo.GetImageEncoders()) { if (ici.MimeType == "image/jpeg") { MemoryStream streamjpg = new MemoryStream(); EncoderParameters eps = new EncoderParameters(1); eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); // or whatever other quality value you want e.Save(streamjpg, ici, eps); // add a frame avi_add(streamjpg.ToArray(), (uint)streamjpg.Length); // write header - so even partial files will play avi_end(e.Width, e.Height, -1); break; } } } catch (Exception) { } }
/// <summary> /// 文字水印 /// </summary> /// <param name="byteData">图片字节数组</param> /// <param name="fileExt">图片扩展名</param> /// <param name="watermarkText">水印文字</param> /// <param name="watermarkStatus">图片水印位置 0=不使用 1=左上 2=中上 3=右上 4=左中 9=右下</param> /// <param name="quality">附加水印图片质量,0-100</param> /// <param name="fontname">字体</param> /// <param name="fontsize">字体大小</param> public static byte[] AddImageSignText(byte[] byteData, string fileExt, string watermarkText, int watermarkStatus, int quality, string fontname, int fontsize) { MemoryStream memoryStream = new MemoryStream(byteData); Image img = Image.FromStream(memoryStream); Graphics g = Graphics.FromImage(img); //设置高质量插值法 g.InterpolationMode = InterpolationMode.HighQualityBicubic; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = SmoothingMode.AntiAlias; g.PixelOffsetMode = PixelOffsetMode.HighQuality; Font drawFont = new Font(fontname, fontsize, FontStyle.Regular, GraphicsUnit.Pixel); SizeF crSize; crSize = g.MeasureString(watermarkText, drawFont); float xpos = 0; float ypos = 0; switch (watermarkStatus) { case 1: xpos = (float)img.Width * (float).01; ypos = (float)img.Height * (float).01; break; case 2: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = (float)img.Height * (float).01; break; case 3: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = (float)img.Height * (float).01; break; case 4: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 5: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 6: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).50) - (crSize.Height / 2); break; case 7: xpos = (float)img.Width * (float).01; ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 8: xpos = ((float)img.Width * (float).50) - (crSize.Width / 2); ypos = ((float)img.Height * (float).99) - crSize.Height; break; case 9: xpos = ((float)img.Width * (float).99) - crSize.Width; ypos = ((float)img.Height * (float).99) - crSize.Height; break; } g.DrawString(watermarkText, drawFont, new SolidBrush(Color.White), xpos + 1, ypos + 1); g.DrawString(watermarkText, drawFont, new SolidBrush(Color.Black), xpos, ypos); ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo ici = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) { ici = codec; } } EncoderParameters encoderParams = new EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) { quality = 80; } qualityParam[0] = quality; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; try { using (MemoryStream ms = new MemoryStream()) { if (ici != null) { img.Save(ms, ici, encoderParams); } else { img.Save(ms, GetFormat(fileExt)); } byte[] buffer = new byte[ms.Length]; ms.Seek(0, SeekOrigin.Begin); ms.Read(buffer, 0, buffer.Length); return(buffer); } } finally { g.Dispose(); img.Dispose(); } }
public void SaveImage(ImageEventArgs e) { ImageCodecInfo myImageCodecInfo; Encoder myEncoder; EncoderParameter myEncoderParameter; EncoderParameters myEncoderParameters; myImageCodecInfo = GetEncoderInfo(EncoderType); myEncoder = Encoder.Quality; myEncoderParameters = new EncoderParameters(1); myEncoderParameter = new EncoderParameter(myEncoder, imageQuality); myEncoderParameters.Param[0] = myEncoderParameter; try { string finalFile = System.IO.Path.Combine(e.FullSaveLocation, e.FullFileName) + "." + e.Extension; e.CapturedImage.Save(finalFile, myImageCodecInfo, myEncoderParameters); // e.CapturedImage.Save(finalFile); // e.CapturedImage.Save("c:\\users\\affan\\desktop\\jjajja.jpeg"); ShowToastForm(finalFile); //this.Invoke(new ShowToastFormInvoker(ShowToastForm), e.FullSaveLocation + ".jpg"); } catch(ArgumentException ex) { Console.WriteLine(ex.Message); } finally { myEncoderParameters.Dispose(); myEncoderParameter.Dispose(); } }
public bool SaveMultipage(List <ScannedImage> images, string location, Func <int, bool> progressCallback) { try { ImageCodecInfo codecInfo = GetCodecForString("TIFF"); if (!progressCallback(0)) { return(false); } PathHelper.EnsureParentDirExists(location); if (images.Count == 1) { var iparams = new EncoderParameters(1); Encoder iparam = Encoder.Compression; var iparamPara = new EncoderParameter(iparam, (long)(EncoderValue.CompressionLZW)); iparams.Param[0] = iparamPara; using (var bitmap = scannedImageRenderer.Render(images[0])) { bitmap.Save(location, codecInfo, iparams); } } else if (images.Count > 1) { Encoder saveEncoder; Encoder compressionEncoder; EncoderParameter SaveEncodeParam; EncoderParameter CompressionEncodeParam; var encoderParams = new EncoderParameters(2); saveEncoder = Encoder.SaveFlag; compressionEncoder = Encoder.Compression; // Save the first page (frame). SaveEncodeParam = new EncoderParameter(saveEncoder, (long)EncoderValue.MultiFrame); CompressionEncodeParam = new EncoderParameter(compressionEncoder, (long)EncoderValue.CompressionLZW); encoderParams.Param[0] = CompressionEncodeParam; encoderParams.Param[1] = SaveEncodeParam; File.Delete(location); using (var bitmap0 = scannedImageRenderer.Render(images[0])) { bitmap0.Save(location, codecInfo, encoderParams); for (int i = 1; i < images.Count; i++) { if (images[i] == null) { break; } if (!progressCallback(i)) { bitmap0.Dispose(); File.Delete(location); return(false); } SaveEncodeParam = new EncoderParameter(saveEncoder, (long)EncoderValue.FrameDimensionPage); CompressionEncodeParam = new EncoderParameter(compressionEncoder, (long)EncoderValue.CompressionLZW); encoderParams.Param[0] = CompressionEncodeParam; encoderParams.Param[1] = SaveEncodeParam; using (var bitmap = scannedImageRenderer.Render(images[i])) { bitmap0.SaveAdd(bitmap, encoderParams); } } SaveEncodeParam = new EncoderParameter(saveEncoder, (long)EncoderValue.Flush); encoderParams.Param[0] = SaveEncodeParam; bitmap0.SaveAdd(encoderParams); } } return(true); } catch (Exception ex) { throw new Exception("Error saving TIFF", ex); } }
private void compress(System.Drawing.Image img, string path, string Extension) { try { EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 60L); ImageCodecInfo jpegCodec = null; if (Extension == ".jpeg") { jpegCodec = GetEncoderInfo("image/jpeg"); } if (Extension == ".bmp") { jpegCodec = GetEncoderInfo("image/bmp"); } if (Extension == ".gif") { jpegCodec = GetEncoderInfo("image/gif"); } if (Extension == ".png") { jpegCodec = GetEncoderInfo("image/png"); } if (Extension == ".jpg") { jpegCodec = GetEncoderInfo("image/jpeg"); } EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; img.Save(path, jpegCodec, encoderParams); } catch (Exception ex) { throw ex; } }
protected abstract void SaveDocument(Document doc, Bitmap image, ImageCodecInfo codec, EncoderParameters encoderParameters);
public void Write(BinaryWriter writer) { EncoderParameters encodeParams = new EncoderParameters(1); encodeParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100); _bitmap.Save(writer.BaseStream, _codecInfo, encodeParams); }
public static string SaveMarkerPhoto(byte[] markerPhoto, bool mini) { var virtualPath = $@"{MarkerPhotos}\{Guid.NewGuid()}.jpg"; var jpgEncoder = GetEncoder(ImageFormat.Jpeg); var siteRoot = GetPublicContent(); if (siteRoot != null) { var savePath = $@"{siteRoot}\{virtualPath}"; using (var stream = new MemoryStream(markerPhoto)) { var myEncoder = Encoder.Quality; var myEncoderParameters = new EncoderParameters(1); var myEncoderParameter = new EncoderParameter(myEncoder, 50L); myEncoderParameters.Param[0] = myEncoderParameter; var firstBitmap = new Bitmap(stream); if (Array.IndexOf(firstBitmap.PropertyIdList, 274) > -1) { var orientation = (int)firstBitmap.GetPropertyItem(274).Value[0]; switch (orientation) { case 1: // No rotation required. break; case 2: firstBitmap.RotateFlip(RotateFlipType.RotateNoneFlipX); break; case 3: firstBitmap.RotateFlip(RotateFlipType.Rotate180FlipNone); break; case 4: firstBitmap.RotateFlip(RotateFlipType.Rotate180FlipX); break; case 5: firstBitmap.RotateFlip(RotateFlipType.Rotate90FlipX); break; case 6: firstBitmap.RotateFlip(RotateFlipType.Rotate90FlipNone); break; case 7: firstBitmap.RotateFlip(RotateFlipType.Rotate270FlipX); break; case 8: firstBitmap.RotateFlip(RotateFlipType.Rotate270FlipNone); break; } // This EXIF data is now invalid and should be removed. firstBitmap.RemovePropertyItem(274); } if (!mini) { firstBitmap.Save(savePath); } else { firstBitmap.Save(savePath, jpgEncoder, myEncoderParameters); } } } else { throw new MyException(Errors.UnknownError); } return(virtualPath); }
private static void Stream(string ip) { Thread.Sleep(300); int miliseconds = DateTime.Now.Millisecond; pipe = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool connected = false; while (!connected) { try { IAsyncResult result = pipe.BeginConnect(new IPEndPoint( IPAddress.Parse(ip), 4578), null, null); connected = result.AsyncWaitHandle.WaitOne(3000, true); } catch (Exception e) { ConsoleLogic.WriteConsole("error at connecting back to receiver"); } } //performSearch = false; int cyclesCount = 0; int fps = 0; int sleepTime = 0; System.Timers.Timer timer = new System.Timers.Timer(1000); timer.Elapsed += (sender, args) => { main.cycleSpeedSend.Text = cyclesCount.ToString(); fps = cyclesCount; sleepTime = (int)(1000 / (((main.FPS.Value - fps) / 60) * 1000)); main.thrSleepTime.Text = sleepTime.ToString(); cyclesCount = 0; }; timer.Enabled = true; Bitmap prevImage = null; while (true) { try { cyclesCount++; //while((DateTime.Now.Millisecond - miliseconds) <= 1000/main.FPS.Value) //{ // Thread.Sleep(1); //} //miliseconds = DateTime.Now.Millisecond; if (fps < main.FPS.Value) { if (main.FPS.Value - fps > 20) { } else { Thread.Sleep((int)(1000 / (((main.FPS.Value - fps) / 60) * 1000))); } } else { } if (!pipe.Connected) { //searchTask.Start(); return; } int sqrSize = (int)main.strImgSize.Value; Bitmap memoryImage = new Bitmap(sqrSize, sqrSize /*, PixelFormat.Format8bppIndexed*/); Size s = new Size(sqrSize, sqrSize); Graphics memoryGraphics = Graphics.FromImage(memoryImage); memoryGraphics.CopyFromScreen(0, 0, 0, 0, s); //Comparison if (prevImage != null) { if (prevImage.Height == memoryImage.Height) { Bitmap prevHolder = memoryImage.Clone() as Bitmap; memoryImage = GetDifferences(prevImage, memoryImage, Color.Pink); prevImage.Dispose(); prevImage = prevHolder; //memoryImage.MakeTransparent(Color.Pink); } else { prevImage = memoryImage.Clone() as Bitmap; } } else { prevImage = memoryImage.Clone() as Bitmap; } //Compress using (var stream = new MemoryStream()) { EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, (long)main.strImgCompression.Value); EncoderParameter colorDepthParam = new EncoderParameter(Encoder.ColorDepth, (long)main.strImgCD.Value); EncoderParameter compressionParam = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionLZW); ImageCodecInfo imageCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(o => o.FormatID == ImageFormat.Jpeg.Guid); EncoderParameters parameters = new EncoderParameters(3); parameters.Param[0] = qualityParam; parameters.Param[1] = colorDepthParam; parameters.Param[2] = compressionParam; // memoryImage.Save(stream, imageCodec, parameters); byte[] compressedData = new byte[LZ4Codec.MaximumOutputSize((int)stream.Length)]; LZ4Codec.Encode(stream.GetBuffer(), compressedData, LZ4Level.L12_MAX); main.dataAmount.Text = stream.Length.ToString(); main.compressedDataAmount.Text = compressedData.Length.ToString(); if (compressedData.Length > 15000) { continue; } pipe.Send(Serializer.ObjectToBytes(new ImageStreamPart(compressedData, stream.Length))); } //using (var stream = new MemoryStream()) //{ // compressedImg.Save(stream, ImageFormat.Jpeg); //} memoryImage.Dispose(); memoryGraphics.Dispose(); //Thread.Sleep(30); //Fix large bitmap size //Serializer.ObjectToBytes( // new ImageConverter().ConvertTo( // memoryImage, // typeof(byte[]))) } catch (Exception e) { ConsoleLogic.WriteConsole("Error at sending image", e); } } }
/// <summary> /// Create By Xu In 2018.09.29 /// Edit By Xu In 2018.10.23 //Add BitMap.Dispose(); /// Edit By Xu In 2018_10_29 //strFileName -> strFilePath ,Meaning You Need't Add ".FileFormat" In "strFilePath" But Must Assign ST_SaveOrLoadImgData.iImgFormat To Figure Out File Format; /// Function: Save Img To Native. /// </summary> /// <param name="strFileName">FilePath+FileName</param> /// <param name="stReadImgData">ST_SaveOrLoadImgData</param> /// <param name="iImgQuality">Low 0->100 High</param> /// <returns></returns> public string SaveImg(string strFilePath, ST_SaveOrLoadImgData stSaveImgData, int iImgQuality) { string strMsg = string.Empty; string strFileName = string.Empty; try { if (strFilePath == null) { return("FilePath_Is_Null"); } switch (stSaveImgData.iImgFormat)//Edit By Xu In 2018_10_30 { case 0: if ( (strFilePath[strFilePath.Length - 4] == 46) && //"." (strFilePath[strFilePath.Length - 3] == 98 || strFilePath[strFilePath.Length - 3] == 66) && //"bB" (strFilePath[strFilePath.Length - 2] == 109 || strFilePath[strFilePath.Length - 2] == 77) && //"mM" (strFilePath[strFilePath.Length - 1] == 112 || strFilePath[strFilePath.Length - 1] == 80) //"pP" ) { strFileName = strFilePath; } else { strFileName = strFilePath + ".bmp"; } break; case 1: if ( (strFilePath[strFilePath.Length - 4] == 46) && (strFilePath[strFilePath.Length - 3] == 106 || strFilePath[strFilePath.Length - 3] == 74) && //"jJ" (strFilePath[strFilePath.Length - 2] == 112 || strFilePath[strFilePath.Length - 2] == 80) && //"pP" (strFilePath[strFilePath.Length - 1] == 103 || strFilePath[strFilePath.Length - 1] == 71) //"gG" ) { strFileName = strFilePath; } else { strFileName = strFilePath + ".jpg"; } break; case 2: SaveImg(strFilePath, stSaveImgData); //.imgdat return("Format_Is_.imgdat"); default: return("File_Format_Params_Err"); } if (stSaveImgData.iImgFormat == 0 && stSaveImgData.bUseOpcv == true) { byte[] byFileName = System.Text.Encoding.Default.GetBytes(strFileName); float[] AfarrParams = new float[3]; AfarrParams[0] = (float)strFileName.Length; AfarrParams[1] = (float)stSaveImgData.iWidth; AfarrParams[2] = (float)stSaveImgData.iHeight; _cvFunc.SaveImgByOpcv(byFileName, stSaveImgData.byImgDataR, stSaveImgData.byImgDataG, stSaveImgData.byImgDataB, AfarrParams); return(strMsg); } Bitmap bmp = new Bitmap(stSaveImgData.iWidth, stSaveImgData.iHeight, PixelFormat.Format24bppRgb); int iWidth = stSaveImgData.iWidth; int iHeight = stSaveImgData.iHeight; int iLength = iWidth * iHeight; //获取图像的BitmapData对像 System.Drawing.Imaging.BitmapData data = bmp.LockBits(new Rectangle(0, 0, iWidth, iHeight), System.Drawing.Imaging.ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format24bppRgb); //循环处理 unsafe { int iOffset = data.Stride - data.Width * 3; byte *ptr = (byte *)(data.Scan0); byte *ptr_b; byte *ptr_g; byte *ptr_r; ptr_b = (byte *)System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(stSaveImgData.byImgDataB, 0); ptr_g = (byte *)System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(stSaveImgData.byImgDataG, 0); ptr_r = (byte *)System.Runtime.InteropServices.Marshal.UnsafeAddrOfPinnedArrayElement(stSaveImgData.byImgDataR, 0); if (iOffset == 0) { for (int i = 0; i < iLength; i++) { *ptr++ = *ptr_b++; *ptr++ = *ptr_g++; *ptr++ = *ptr_r++; } } else { for (int i = 0; i < iHeight; i++) { for (int j = 0; j < iWidth; j++) { *ptr++ = *ptr_b++; *ptr++ = *ptr_g++; *ptr++ = *ptr_r++; } ptr += iOffset; } } } switch (stSaveImgData.iImgFormat) { case 0: bmp.Save(strFileName, System.Drawing.Imaging.ImageFormat.Bmp); break; case 1: EncoderParameter p; EncoderParameters ps; ps = new EncoderParameters(1); if (iImgQuality > 100) { iImgQuality = 100; } else if (iImgQuality < 0) { iImgQuality = 80; } p = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, iImgQuality); ps.Param[0] = p; bmp.Save(strFileName, GetCodecInfo("image/jpeg"), ps); break; default: bmp.Save(strFileName, System.Drawing.Imaging.ImageFormat.Bmp); break; } bmp.Dispose();//Edit By Xu In 2018.10.23 } catch (Exception e) { strMsg += "SaveImgErr" + e.Message.ToString(); } return(strMsg); }