public static void Resize(this Image source, String newFilename, Size newSize, long quality, ContentAlignment contentAlignment, ThumbMode mode) { Image image = source.Resize(newSize, quality, contentAlignment, mode); using (EncoderParameters encoderParams = new EncoderParameters(1)) { using (EncoderParameter parameter = (encoderParams.Param[0] = new EncoderParameter(Encoder.Quality, quality))) { ImageCodecInfo encoder = null; //取得擴展名 string ext = Path.GetExtension(newFilename); if (string.IsNullOrEmpty(ext)) ext = ".jpg"; //根據擴展名得到解碼、編碼器 foreach (ImageCodecInfo codecInfo in ImageCodecInfo.GetImageEncoders()) { if (Regex.IsMatch(codecInfo.FilenameExtension, string.Format(@"(;|^)\*\{0}(;|$)", ext), RegexOptions.IgnoreCase)) { encoder = codecInfo; break; } } DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(newFilename)); if(dir.Exists == false) dir.Create(); image.Save(newFilename, encoder, encoderParams); } } }
private void modImage(RotateFlipType rft) { if (this._filename.Length == 0) { return; } this._bmp.RotateFlip(rft); this.imageBox.Image = this._bmp; this.imageBox.ZoomToFit(); if (this.checkBoxSave.Checked) { if (".jpg.JPG.jpeg.JPEG".Contains(Path.GetExtension(this._filename))) { // 20161016: prevent jpg quality loss requires to set the quality level explicitly ImageCodecInfo jgpEncoder = this.GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 100L); myEncoderParameters.Param[0] = myEncoderParameter; this._bmp.Save(this._filename, jgpEncoder, myEncoderParameters); myEncoderParameter.Dispose(); } else { // tread other file type as they are this._bmp.Save(this._filename); } } try { this._parent.Focus(); } catch {; } }
static void Main(string[] args) { FileSize("noname.jpg"); var image = new Bitmap("noname.jpg"); var jgpEncoder = GetEncoder(ImageFormat.Jpeg); var myEncoder = Encoder.Quality; var myEncoderParameters = new EncoderParameters(1); var myEncoderParameter = new EncoderParameter(myEncoder, 50L); myEncoderParameters.Param[0] = myEncoderParameter; image.Save(@"TestPhotoQualityFifty.jpg", jgpEncoder, myEncoderParameters); FileSize("TestPhotoQualityFifty.jpg"); myEncoderParameter = new EncoderParameter(myEncoder, 100L); myEncoderParameters.Param[0] = myEncoderParameter; image.Save(@"TestPhotoQualityHundred.jpg", jgpEncoder, myEncoderParameters); FileSize("TestPhotoQualityHundred.jpg"); myEncoderParameter = new EncoderParameter(myEncoder, 70L); myEncoderParameters.Param[0] = myEncoderParameter; image.Save(@"TestPhotoQualityZero.jpg", jgpEncoder, myEncoderParameters); FileSize("TestPhotoQualityZero.jpg"); Console.ReadLine(); }
/* * 使用例子: * ImageCodecInfo jgpEncoder = PaintTools.GetEncoderByFormat(ImageFormat.Jpeg); * EncoderParameters encoderParameters = PaintTools.GetEncoderParametersByNumber(100); * bitMapCut.Save(AppDomain.CurrentDomain.BaseDirectory + savePicPath + "_.jpg", jgpEncoder, encoderParameters); */ /// <summary> /// 设置图片品质 /// </summary> /// <param name="compressionRate">100是最好品质</param> /// <returns></returns> public static EncoderParameters GetEncoderParametersByNumber(int compressionRate = 100) { System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compressionRate);//这里设品质 encoderParameters.Param[0] = encoderParameter; return(encoderParameters); }
protected static void KucukBoyut(System.Drawing.Image orjinalFoto, int boyut, string dosyaAdi) { System.Drawing.Bitmap islenmisFotograf = null; System.Drawing.Graphics grafik = null; int hedefGenislik = boyut; int hedefYukseklik = boyut; int new_width, new_height; new_height = (int)Math.Round(((float)orjinalFoto.Height * (float)boyut) / (float)orjinalFoto.Width); new_width = hedefGenislik; hedefYukseklik = new_height; new_width = new_width > hedefGenislik ? hedefGenislik : new_width; new_height = new_height > hedefYukseklik ? hedefYukseklik : new_height; if (new_height > 210) { hedefYukseklik = 210; } islenmisFotograf = new System.Drawing.Bitmap(hedefGenislik, hedefYukseklik); grafik = System.Drawing.Graphics.FromImage(islenmisFotograf); grafik.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White), new System.Drawing.Rectangle(0, 0, hedefGenislik, hedefYukseklik)); int paste_x = (hedefGenislik - new_width) / 2; int paste_y = (hedefYukseklik - new_height) / 2; grafik.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; grafik.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; grafik.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default; System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1]; System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1); eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L); grafik.DrawImage(orjinalFoto, paste_x, paste_y, new_width, new_height); islenmisFotograf.Save(HttpContext.Current.Server.MapPath("../Urunler/Logo/" + dosyaAdi), codec, eParams); }
} // end of color //使用方法调用GenerateHighThumbnail()方法即可 //参数oldImagePath表示要被缩放的图片路径 //参数newImagePath表示缩放后保存的图片路径 //参数width和height分别是缩放范围宽和高 public static void GenerateHighThumbnail(string oldImagePath, string newImagePath, int width, int height) { System.Drawing.Image oldImage = System.Drawing.Image.FromFile(oldImagePath); int newWidth = AdjustSize(width, height, oldImage.Width, oldImage.Height).Width; int newHeight = AdjustSize(width, height, oldImage.Width, oldImage.Height).Height; //。。。。。。。。。。。 System.Drawing.Image thumbnailImage = oldImage.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero); System.Drawing.Bitmap bm = new System.Drawing.Bitmap(thumbnailImage); //处理JPG质量的函数 System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg"); if (ici != null) { System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1); ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100); bm.Save(newImagePath, ici, ep); //释放所有资源,不释放,可能会出错误。 ep.Dispose(); ep = null; } ici = null; bm.Dispose(); bm = null; thumbnailImage.Dispose(); thumbnailImage = null; oldImage.Dispose(); oldImage = null; }
/// <summary> /// Resize the image to the specified width and height. /// </summary> /// <param name="image">The image to resize.</param> /// <param name="width">The width to resize to.</param> /// <param name="height">The height to resize to.</param> /// <returns>The resized image.</returns> private static void ResizeImage(Image image, int width, int height, string path) { int quality = 90; System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); var destRect = new Rectangle(0, 0, width, height); var destImage = new Bitmap(width, height, PixelFormat.Format24bppRgb); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var graphics = Graphics.FromImage(destImage)) { graphics.CompositingMode = CompositingMode.SourceCopy; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); } } destImage.Save(path, GetImageCodeInfo("image/jpeg"), encoderParameters); }
public void ConvertToSinglePageTiffs(string fileName, string destFolder) { Image image = Image.FromFile(fileName); ImageCodecInfo codecInfo = GetCodecInfo(TIFF_CODEC); FrameDimension frameDim = new FrameDimension(image.FrameDimensionsList[0]); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, ENCODING_SCHEME); for (int i = 0; i < image.GetFrameCount(frameDim); i++) { image.SelectActiveFrame(frameDim, i); string fileNameWOExt = Path.GetFileNameWithoutExtension(fileName); string newFileName = string.Concat(fileNameWOExt, "_", (i + 1).ToString(), TIFF_FILE_EXTENSION); string folder = Path.Combine(Path.GetDirectoryName(fileName), destFolder); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } image.Save(Path.Combine(folder, newFileName), codecInfo, encoderParams); } }
public static void CompressImage(Image sourceImage, int imageQuality, string savePath) { try { //Create an ImageCodecInfo-object for the codec information ImageCodecInfo jpegCodec = null; //Set quality factor for compression EncoderParameter imageQualitysParameter = new EncoderParameter( System.Drawing.Imaging.Encoder.Quality, imageQuality); //List all avaible codecs (system wide) ImageCodecInfo[] alleCodecs = ImageCodecInfo.GetImageEncoders(); EncoderParameters codecParameter = new EncoderParameters(1); codecParameter.Param[0] = imageQualitysParameter; //Find and choose JPEG codec for (int i = 0; i < alleCodecs.Length; i++) { if (alleCodecs[i].MimeType == "image/jpeg") { jpegCodec = alleCodecs[i]; break; } } //Save compressed image sourceImage.Save(HttpContext.Current.Server.MapPath(savePath), jpegCodec, codecParameter); } catch (Exception ex) { } }
public ActionResult Thumbnail(string path) { var myCallback = new Image.GetThumbnailImageAbort(ThumbnailCallback); var paths = new List<string>(2); BuildPath(path, out folderPath, out resourcePath); var folder = session.OpenFolder(folderPath + "/"); var resource = folder.GetResource(resourcePath + "/"); var sourceStream = resource.GetReadStream(); Bitmap bitmap = null; try { bitmap = new Bitmap(sourceStream); } catch (Exception) { var fs = new FileStream(Server.MapPath("~/Content/kendo/2014.2.716/Bootstrap/imagebrowser.png"), FileMode.Open); var tempBs = new byte[fs.Length]; fs.Read(tempBs, 0, tempBs.Length); return new FileContentResult(tempBs, "image/jpeg"); } var myThumbnail = bitmap.GetThumbnailImage(84, 70, myCallback, IntPtr.Zero); var ms = new MemoryStream(); var myEncoderParameters = new EncoderParameters(1); var myEncoderParameter = new EncoderParameter(Encoder.Quality, 25L); myEncoderParameters.Param[0] = myEncoderParameter; myThumbnail.Save(ms, GetEncoderInfo("image/jpeg"), myEncoderParameters); ms.Position = 0; var bytes = ms.ToArray(); return new FileContentResult(bytes, "image/jpeg"); }
static async Task ConvertImages() { var folders = new List<string> { @"day-1", @"day-2", @"day-3", @"day-4", @"day-5", @"day-6" }; //Test var testImg = Guid.Parse("13911e38-af31-48eb-a39d-b5e695124351"); var allFiles = folders .Select(folder => ExtractImageMetaData(folder)) .SelectMany(img => img) //.Where(f => f.Id == testImg) .ToArray(); var numFiles = allFiles.Count(); const long quality = 100L; var qualityParam = System.Drawing.Imaging.Encoder.Quality; var jpgEncoder = ImageCodecInfo.GetImageDecoders().First(enc => enc.FormatID == ImageFormat.Jpeg.Guid); var parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(qualityParam, quality); await Task.WhenAll(allFiles //.Take(100) .Select(file => CopyImage(file, jpgEncoder, parameters))); Debugger.Break(); }
private void sendscreen(string res, int v) { try { int width = Convert.ToInt32(res.Split('x')[0]); int height = Convert.ToInt32(res.Split('x')[1]); using (Bitmap b = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height)) { using (Graphics g = Graphics.FromImage(b)) { g.CopyFromScreen(0, 0, 0, 0, b.Size); using (Image tmp = b.GetThumbnailImage(width, height, null, System.IntPtr.Zero)) { using (Bitmap thumBitmap = new Bitmap(tmp)) { ImageCodecInfo jgpEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, v); myEncoderParameters.Param[0] = myEncoderParameter; using (MemoryStream ms = new MemoryStream()) { thumBitmap.Save(ms, jgpEncoder, myEncoderParameters); Send("RemoteDesktop" + Convert.ToBase64String(ms.ToArray())); } } } } } } catch { } }
public static bool TakeScreenshot(int quality_quotient) { Bitmap resultant = null; Graphics gfxScreenshot = null; latestScreenshot = new MemoryStream(); try { resultant = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format32bppArgb); gfxScreenshot = Graphics.FromImage(resultant); gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); } catch { return false; } ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); // Setting the picture quality EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, (long)quality_quotient); myEncoderParameters.Param[0] = myEncoderParameter; resultant.Save(latestScreenshot, jgpEncoder, myEncoderParameters); return true; }
//http://social.msdn.microsoft.com/forums/en-US/wpf/thread/0f037b9c-779d-45ad-b797-01c25999491b public static BitmapImage ImageFromGDIPlus(byte[] bytes) { var guid = Guid.NewGuid(); if (Directory.Exists(@"C:\Temp\") == false) Directory.CreateDirectory(@"C:\Temp\"); var stream = new MemoryStream(bytes); var badMetadataImage = new Bitmap(stream); ImageCodecInfo myImageCodecInfo; Encoder myEncoder; EncoderParameter myEncoderParameter; EncoderParameters myEncoderParameters; // 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 image as a JPEG file with quality level 75. myEncoderParameter = new EncoderParameter(myEncoder, 75L); myEncoderParameters.Param[0] = myEncoderParameter; badMetadataImage.Save(@"C:\Temp\" + guid + ".bmp", myImageCodecInfo, myEncoderParameters); // Create the source to use as the tb source var bi = new BitmapImage(); bi.BeginInit(); bi.UriSource = new Uri(@"C:\Temp\" + guid + ".bmp", UriKind.Absolute); bi.EndInit(); return bi; }
private static void GenerateThumbnail(HttpPostedFileBase file, string rootFolder, string fileName) { using (var image = Image.FromStream(file.InputStream, true, true)) /* Creates Image from specified data stream */ { using (var thumb = image.GetThumbnailImage( 100, /* width*/ 100, /* height*/ () => false, IntPtr.Zero)) { var jpgInfo = ImageCodecInfo.GetImageEncoders().Where(codecInfo => codecInfo.MimeType == "image/png").First(); /* Returns array of image encoder objects built into GDI+ */ using (var encParams = new EncoderParameters(1)) { var appDataThumbnailPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, rootFolder, "thumbnails"); if (!Directory.Exists(appDataThumbnailPath)) { Directory.CreateDirectory(appDataThumbnailPath); } string outputPath = Path.Combine(appDataThumbnailPath, "thumb_" + fileName); long quality = 100; encParams.Param[0] = new EncoderParameter(Encoder.Quality, quality); thumb.Save(outputPath, jpgInfo, encParams); } } } }
/// <summary> /// 保存到Jpeg图片,且可以设置压缩质量 /// </summary> /// <param name="image"></param> /// <param name="filename">保存路径</param> /// <param name="quality">压缩质量</param> public static void SaveJpeg(this Image image, string filename, long quality) { var encoder = ImageCodecInfo.GetImageEncoders().First( c => c.FormatID == ImageFormat.Jpeg.Guid); var parameters = new EncoderParameters(); parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); image.Save(filename, encoder, parameters); }
public static byte[] CompressImage(Image ImageToCompress, long CompressionLevel) { //grab the memory stream to save into using (var MemoryStreamToSave = new MemoryStream()) { //declare the parameters var EncoderParams = new EncoderParameters(1); //set the compression level EncoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, CompressionLevel); //grab the codec info var EncoderInfo = GetEncoderInfo("image/jpeg"); //go save the image to the memory stream ImageToCompress.Save(MemoryStreamToSave, EncoderInfo, EncoderParams); //close the memory stream MemoryStreamToSave.Flush(); //close the memory stream MemoryStreamToSave.Close(); //return the byte array now return MemoryStreamToSave.ToArray(); } }
public static void BmpSave(Bitmap newBmp, string outFile) { EncoderParameters encoderParams = new EncoderParameters(); long[] quality = new long[1]; quality[0] = 100; EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。 ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICI = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICI = arrayICI[x];//设置JPEG编码 break; } } if (jpegICI != null) { newBmp.Save(outFile, jpegICI, encoderParams); } else { newBmp.Save(outFile, ImageFormat.Jpeg); } newBmp.Dispose(); }
public static void Save(Image image, int maxWidth, int maxHeight, int quality, string filePath) { if (image != null || !image.Equals(0)) { int originalWidth = image.Width; int originalHeight = image.Height; float ratioX = maxWidth / (float)originalWidth; float ratioY = maxHeight / (float)originalHeight; float ratio = Math.Min(ratioX, ratioY); int newWidth = (int)(originalWidth * ratio); int newHeight = (int)(originalHeight * ratio); newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb); 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); } ImageCodecInfo imageCodecInfo = GetEncoderInfo(ImageFormat.Jpeg); System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality; encoderParameters = new EncoderParameters(1); EncoderParameter encoderParameter = new EncoderParameter(encoder, quality); encoderParameters.Param[0] = encoderParameter; newImage.Save(filePath, imageCodecInfo, encoderParameters); } }
/// <summary> /// Saves an image as a jpeg image, with the given quality /// </summary> /// <param name="path">Path to which the image would be saved.</param> /// <param name="quality">An integer from 0 to 100, with 100 being the /// highest quality</param> /// <exception cref="ArgumentOutOfRangeException"> /// An invalid value was entered for image quality. /// </exception> public void SavePNG(Image[] images, int quality, string workspace) { //ensure the quality is within the correct range if ((quality < 0) || (quality > 100)) { //create the error message 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 a helpful exception throw new ArgumentOutOfRangeException(error); } //create an encoder parameter for the image quality var qualityParam = new EncoderParameter(Encoder.Quality, quality); //get the jpeg codec ImageCodecInfo jpegCodec = converter.GetEncoderInfo("image/png"); //create a collection of all parameters that we will pass to the encoder var encoderParams = new EncoderParameters(1); //set the quality parameter for the codec encoderParams.Param[0] = qualityParam; //save the images using the codec and the parameters //each image will be saved into it's folder for (int i = 0; i < images.Length; i++) { for (int j = 0; j < dirs.Length; j++) { string desination = (path + splitter + workspace + dirs[i]); Check(desination); images[i].Save(desination, jpegCodec, encoderParams); } } }
/// <summary> /// Takes a screen-size + internal bezel width sized bitmap and crops it to remove the area taken up by the bezels. Making the image appear as if it was seen through a window. /// </summary> /// <param name="filePaths">The file paths.</param> /// <remarks> /// Writes a file of the same name with -wallpapered appended to the end in JPEG format to the same location as the source. /// </remarks> public static void Main(String[] filePaths) { if(filePaths.Length < 1) { DisplayInstructions(); return; } foreach(var filePath in filePaths) { String fileName = Path.GetFileNameWithoutExtension(filePath); String fileDirectory = Path.GetDirectoryName(filePath); String jpgFilePath = String.Format("{0}{1}{2}-wallpapered.jpg", fileDirectory, Path.DirectorySeparatorChar, fileName); using(Bitmap sourceBitmap = new Bitmap(filePath)) { //Check size if(sourceBitmap.Width != TotalMonitorWidth || sourceBitmap.Height != MaximumMonitorHeight) { DisplayInstructions(); continue; } Bitmap wallpaper = CreateWallpaper(sourceBitmap); //Save as JPEG var jpegImageCodecInfo = GetEncoderInfo("image/jpeg"); var qualityEncoder = Encoder.Quality; var encoderParameters = new EncoderParameters(1); var encoderParameter = new EncoderParameter(qualityEncoder, (Int64)JPEGQuality); encoderParameters.Param[0] = encoderParameter; wallpaper.Save(jpgFilePath, jpegImageCodecInfo, encoderParameters); } } }
public void BaseCreateResponsive(ImageCreateResponsive method) { var mediaType = new MediaTypes(this.Strategy.Session).Jpeg; byte[] content; // Stream should be left open for Save to work using (Stream stream = new MemoryStream(this.Original.Content)) { var responsive = new Bitmap(stream); responsive = responsive.Rotate(); responsive = responsive.MaxHeight(method.MaxHeight ?? 600); var encoder = ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.MimeType == mediaType.Name); var encoderParams = new EncoderParameters(1); var qualityParam = Encoder.Quality; encoderParams.Param[0] = new EncoderParameter(qualityParam, 72L); content = responsive.Save(encoder, encoderParams); } if (!this.ExistResponsive || !content.SequenceEqual(this.Responsive.Content)) { if (this.ExistResponsive) { this.Responsive.Delete(); } this.Responsive = new MediaBuilder(this.Strategy.Session).WithContent(content).WithMediaType(mediaType).Build(); } }
public static EncoderParameters getParameters(int jpegQuality, ScreenshotFormat format) { EncoderParameters result; switch(format) { case ScreenshotFormat.BMP: result = new EncoderParameters(1); result.Param[0] = new EncoderParameter(Encoder.ColorDepth, 24); break; case ScreenshotFormat.JPEG: result = new EncoderParameters(1); result.Param[0] = new EncoderParameter(Encoder.Quality, jpegQuality); break; case ScreenshotFormat.TIFF: result = new EncoderParameters(2); EncoderParameter parameter = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionLZW); result.Param[0] = parameter; parameter = new EncoderParameter(Encoder.SaveFlag, (long)EncoderValue.LastFrame); result.Param[1] = parameter; break; default: result = new EncoderParameters(2); result.Param[0] = new EncoderParameter(Encoder.Compression,(long)EncoderValue.CompressionCCITT4); result.Param[1] = new EncoderParameter(Encoder.ColorDepth, (long)24); break; } return result; }
public byte[] Capture() { if (_camDriver.IsVideoStarted() == false) { _camDriver.StartVideo(); } // wait for the camera to capture something //if (_camDriver.Capture()) //{ _camEvent.WaitOne(); if (_captureStream == null) { _captureStream = new MemoryStream(); } ImageCodecInfo jpgEncoder = ImageCodecInfo.GetImageEncoders().Single(x => x.FormatDescription == "JPEG"); System.Drawing.Imaging.Encoder encoder2 = System.Drawing.Imaging.Encoder.Quality; EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters(1); EncoderParameter parameter = new EncoderParameter(encoder2, 50L); parameters.Param[0] = parameter; _captureStream.Seek(0, SeekOrigin.Begin); _camImage.Save(_captureStream, jpgEncoder, parameters); //_camImage.Save(_captureStream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] buffer = new byte[_captureStream.Length]; Console.WriteLine("Sending image with size " + buffer.Length); //_captureStream.Read(buffer,0,(int)_captureStream.Length); buffer = _captureStream.ToArray(); return buffer; //return b; }
public static Stream ResizeImage(Stream originalImage, int canvasWidth, int canvasHeight) { using (Image img = Image.FromStream(originalImage)) { Image resizedImage = ResizeImage(img, canvasWidth, canvasHeight); System.Drawing.Imaging.ImageCodecInfo info = ImageCodecInfo.GetImageEncoders() .Where(codec => String.Compare(codec.FilenameExtension, "*.png", true) == 0) .FirstOrDefault(); //MemoryStream stream = new MemoryStream(); MemoryStream stream = new MemoryStream(); if (info != null) { EncoderParameters encoderParameters; encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); resizedImage.Save(stream, info, encoderParameters); } return stream; } }
public static byte[] GetBytes(this Bitmap bitmap, OutputFormat outputFormat) { using (var memStream = new MemoryStream()) { bitmap.MakeTransparent(BackgroundColour); switch (outputFormat) { case OutputFormat.Jpeg: bitmap.Save(memStream, ImageFormat.Jpeg); break; case OutputFormat.Gif: bitmap.Save(memStream, ImageFormat.Gif); break; case OutputFormat.Png: bitmap.Save(memStream, ImageFormat.Png); break; case OutputFormat.HighQualityJpeg: var p = new EncoderParameters(1); p.Param[0] = new EncoderParameter(Encoder.Quality, (long)95); bitmap.Save(memStream, GetImageCodeInfo("image/jpeg"), p); break; } return memStream.ToArray(); } }
public static void Process(ClientPacket.Screen screen) { Screen.power = screen.Power; if (Screen.power != 0) { //屏幕 if (screen.Quality != 0) { ps = new EncoderParameters(1); ps.Param[0] = new EncoderParameter(Encoder.Quality, screen.Quality); } if (Screen.thread == null || !Screen.thread.IsAlive) { Screen.thread = new Thread(new ThreadStart(Work)); Screen.thread.Start(); } //鼠标 if (screen.mouse != null) NativeMethods.mouse_event(screen.mouse.dwFlags, screen.mouse.dx, screen.mouse.dy, 0, 0); //键盘 if (screen.keybd != null) NativeMethods.keybd_event(screen.keybd.bVk, screen.keybd.bScan, screen.keybd.dwFlags, 0); } }
public void CreateThumnail(HttpPostedFileBase file, string folderPath, string fileSuffix) { using (var image = Image.FromStream(file.InputStream, true, true)) /* Creates Image from specified data stream */ { using (var thumb = image.GetThumbnailImage( 36, /* width*/ 30, /* height*/ () => false, IntPtr.Zero)) { var jpgInfo = ImageCodecInfo.GetImageEncoders().Where(codecInfo => codecInfo.MimeType == "image/png").First(); /* Returns array of image encoder objects built into GDI+ */ using (var encParams = new EncoderParameters(1)) { if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); } //Change file extention to thumb var fileName = Path.ChangeExtension(file.FileName, "thumb"); string outputPath = Path.Combine(folderPath, GetFileNameWithSuffix(fileName, fileSuffix)); long quality = 100; encParams.Param[0] = new EncoderParameter(Encoder.Quality, quality); thumb.Save(outputPath, jpgInfo, encParams); //thumb.Save(Path.ChangeExtension(file.FileName, "thumb")) } } } }
public static void work() { keepGoing = true; Task.Factory.StartNew(()=>check()); do { Bitmap img = GetScreenShot(); ImageCodecInfo[] codec = ImageCodecInfo.GetImageEncoders(); // initialisation d'un tableau de dimension 2 de parametres d'encodages EncoderParameters encodeurs = new EncoderParameters(2); // parametre qualite EncoderParameter qualite = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality,quality); // Parametre compression EncoderParameter compression = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, compress); // remplir tableau parametre encodeurs.Param[0] = qualite; encodeurs.Param[1] = compression; using (MemoryStream stm = new MemoryStream()) { img.Save(stm, codec[1], encodeurs); if (Cnx.sendArray(stm.ToArray(), "04")) { Console.WriteLine("success "); } } Thread.Sleep(sleeptime); } while (keepGoing); }
public static void SaveJpegToStreamWithCompressionSetting(Image image, long compression, Stream savestream) { var eps = new EncoderParameters(1); eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compression); var ici = GetEncoderInfo("image/jpeg"); image.Save(savestream, ici, eps); }
public IEnumerable<ProcessFileResult> ProcessFiles(string[] files, Settings settings) { ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg); var encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, settings.Quality); foreach (var file in files) { using (var original = (Bitmap)Image.FromFile(file)) { string fileName = Path.Combine(settings.OutputDir, Path.GetFileName(file)); if (!settings.OverwriteFiles && File.Exists(fileName)) { yield return new ProcessFileResult { ErrorMessage = "File name is the same." }; } if (settings.Width > 0 || settings.Height > 0) { using (Bitmap scaled = original.Scale(settings.Size)) { AddLogoOrText(scaled, settings); scaled.Save(fileName, jgpEncoder, encoderParameters); } } else { AddLogoOrText(original, settings); original.Save(fileName, jgpEncoder, encoderParameters); } yield return new ProcessFileResult {FileInfo = new FileInfo(fileName)}; } } }
/// <summary> /// Save an Image as a JPeg with a given compression /// Note: Filename suffix will not affect mime type which will be Jpeg. /// </summary> /// <param name="image">Image: Image to save</param> /// <param name="fileName">String: File name to save the image as. Note: suffix will not affect mime type which will be Jpeg.</param> /// <param name="compression">Long: Value between 0 and 100.</param> private static void SaveJpegWithCompressionSetting(Image image, string fileName, long compression) { var eps = new EncoderParameters(1); eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, compression); var ici = GetEncoderInfo("image/jpeg"); image.Save(fileName, ici, eps); }
public static void SaveJPG100(this Bitmap image, MemoryStream stream) { stream.Flush(); EncoderParameters encoderParameters = new EncoderParameters(1); encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 75L); image.Save(stream, GetEncoder(ImageFormat.Jpeg), encoderParameters); }
public static void SaveToFileInQuality(this Image image, string path, ImageFormat format) { var parameters = new EncoderParameters(); parameters.Param[0] = new EncoderParameter(Encoder.Quality, new long[] { 90 }); var encoder = ImageCodecInfo.GetImageEncoders().First(x => x.FormatID == format.Guid); image.Save(path, encoder, parameters); }
/// <summary> /// Convert Tiff image to another mime-type bitmap /// </summary> /// <param name="tiffImage">Source TIFF file</param> /// <param name="mimeType">Desired result mime-type</param> /// <returns>Converted image</returns> public Bitmap ConvertTiffToBitmap(Image tiffImage, string mimeType) { var imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(encoder => encoder.MimeType == "image/tiff"); if (imageCodecInfo == null) { return null; } Bitmap sourceImg; using (var memoryStream = new MemoryStream()) { // Setting encode params var imageEncoderParams = new EncoderParameters(1); imageEncoderParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L); tiffImage.Save(memoryStream, imageCodecInfo, imageEncoderParams); tiffImage.Dispose(); var ic = new ImageConverter(); // Reading stream data to new image var tempTiffImage = (Image)ic.ConvertFrom(memoryStream.GetBuffer()); // Setting new result mime-type imageCodecInfo = ImageCodecInfo.GetImageEncoders().FirstOrDefault(encoder => encoder.MimeType == mimeType); if (tempTiffImage != null) tempTiffImage.Save(memoryStream, imageCodecInfo, imageEncoderParams); sourceImg = new Bitmap(Image.FromStream(memoryStream, true)); } return sourceImg; }
/// <summary> /// 調整圖片壓縮解析度 /// </summary> public static string ToBase64String_x1(Bitmap newBmp, ImageFormat iFormat) { MemoryStream ms = new MemoryStream(); //save ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Jpeg); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 30L); myEncoderParameters.Param[0] = myEncoderParameter; newBmp.Save(ms, jgpEncoder, myEncoderParameters); //Bitmap new2Bmp = new Bitmap(ms); //new2Bmp.Save(@"c:\test002.jpg", iFormat); //newBmp.Save(ms, iFormat); ms.Seek(0, SeekOrigin.Begin); //建立一個byte //並且定義長度為MemoryStream的長度 byte[] bytes = new byte[ms.Length]; //MemoryStream讀取資料 ms.Read(bytes, 0, (int)ms.Length); ms.Close(); return Convert.ToBase64String(bytes); }
/// <summary> /// 将<paramref name="sourceStream"/>压缩大小 /// </summary> /// <param name="sourceStream"></param> /// <param name="ouputStream"></param> /// <param name="width"></param> /// <param name="height"></param> public static void Compress(Stream sourceStream, Stream ouputStream, int width, int height, bool highQuality) { System.Drawing.Image source = null; Graphics gdiobj = null; try { source = System.Drawing.Image.FromStream(sourceStream); using (Bitmap img = new Bitmap(width, height)) { img.SetResolution(source.HorizontalResolution, source.VerticalResolution); gdiobj = Graphics.FromImage(img); gdiobj.CompositingQuality = highQuality ? CompositingQuality.HighQuality : CompositingQuality.HighSpeed; gdiobj.SmoothingMode = highQuality ? SmoothingMode.HighQuality : SmoothingMode.HighSpeed; gdiobj.InterpolationMode = highQuality ? InterpolationMode.HighQualityBicubic : InterpolationMode.Low; gdiobj.PixelOffsetMode = highQuality? PixelOffsetMode.HighQuality: PixelOffsetMode.HighSpeed; gdiobj.FillRectangle(new SolidBrush(System.Drawing.Color.FromArgb(0, System.Drawing.Color.Transparent)), 0, 0, width, height); Rectangle destrect = new Rectangle(0, 0, width, height); gdiobj.DrawImage(source, destrect, 0, 0, source.Width, source.Height, GraphicsUnit.Pixel); using (System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1)) { ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)1); if (!highQuality) { img.Save(ouputStream, ImageFormat.Png); } else { System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/png"); if (ici != null) { img.Save(ouputStream, ici, ep); } else { img.Save(ouputStream, System.Drawing.Imaging.ImageFormat.Png); } } } } } catch (Exception ex) { throw ex; } finally { if (source != null) { source.Dispose(); } if (gdiobj != null) { gdiobj.Dispose(); } } }
public static string extractImagefromPdf(string pdfSource) { //var pdfsource = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\marksheet.pdf-mysigned"; PdfReader pdf = new PdfReader(pdfSource); RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(pdfSource); try { PdfDictionary pd = pdf.GetPageN(1); PdfDictionary res = (PdfDictionary)PdfReader.GetPdfObject(pd.Get(PdfName.RESOURCES)); PdfDictionary xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT)); if (xobj != null) { foreach (PdfName name in xobj.Keys) { PdfObject obj = xobj.Get(name); if (obj.IsIndirect()) { PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj); PdfName type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE)); if (PdfName.IMAGE.Equals(type)) { int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture)); PdfObject pdfObj = pdf.GetPdfObject(XrefIndex); PdfStream pdfStrem = (PdfStream)pdfObj; byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem); if ((bytes != null)) { using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes)) { memStream.Position = 0; System.Drawing.Image img = System.Drawing.Image.FromStream(memStream); var outputPath = System.AppDomain.CurrentDomain.BaseDirectory + "App_Data\\"; if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } string path = Path.Combine(outputPath, String.Format(@"{0}.bmp", 1)); System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1); parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0); System.Drawing.Imaging.ImageCodecInfo jpegEncoder = GetImageEncoder("BMP"); img.Save(path, jpegEncoder, parms); } } } } } } return("completed"); } catch (Exception e) { return(e.Message.ToString()); } finally { pdf.Close(); } }
/// <summary> /// 保存图片 /// </summary> /// <param name="image">Image 对象</param> /// <param name="savePath">保存路径</param> /// <param name="ici">指定格式的编解码参数</param> private static void SaveImage(Image image, string savePath, ImageCodecInfo ici) { //设置 原图片 对象的 EncoderParameters 对象 System.Drawing.Imaging.EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters(1); parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ((long)100)); image.Save(savePath, ici, parameters); parameters.Dispose(); }
//-- //-- save bitmap object to JPEG of specified quality level //-- private static void BitmapToJPEG(Bitmap objBitmap, string strFilename, long lngCompression = 75) { System.Drawing.Imaging.EncoderParameters objEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.ImageCodecInfo objImageCodecInfo = GetEncoderInfo("image/jpeg"); objEncoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, lngCompression); objBitmap.Save(strFilename, objImageCodecInfo, objEncoderParameters); }
public static void Save(this Bitmap image, Stream rstream, string mimeType = "image/png") { System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().First(f => f.MimeType == mimeType); System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1); eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); image.Save(rstream, codec, eParams); rstream.Seek(0, SeekOrigin.Begin); }
/// <summary> /// 保存扫描的申请单 /// </summary> /// <param name="bmp"></param> /// <returns></returns> private bool SaveScanImg(Bitmap bmp) { //创建一个扫描图像类 ScanData oneScan = new ScanData(); oneScan.申请ID = _str申请ID; oneScan.扫描ID = SqlHelper.GetNumGuid().ToString(); oneScan.扫描信息.存储ID = 存储ID; oneScan.扫描信息.扫描人 = 扫描人; oneScan.扫描信息.扫描时间 = _scanModel.GetServerDate(); oneScan.扫描信息.文件名 = Guid.NewGuid().ToString("N"); oneScan.扫描信息.申请日期 = 申请日期; oneScan.扫描信息.CopyBasePro(oneScan); try { //保存临时文件 var eps = new System.Drawing.Imaging.EncoderParameters(1); var ep = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 85L); eps.Param[0] = ep; var jpsEncoder = GetEncoder(ImageFormat.Jpeg); FTPFileHelp ftpHelper = new FTPFileHelp(); initFTP(_dbQuery, 存储ID, out ftpHelper); string vPath = ftpHelper.VPath + "//" + oneScan.扫描信息.申请日期.ToString("yyyyMMdd") + "//" + oneScan.申请ID + "//apply//"; string tmpFile = System.Windows.Forms.Application.StartupPath + @"\Temp" + vPath.Replace("//", "\\"); if (Directory.Exists(tmpFile) == false) { Directory.CreateDirectory(tmpFile); } tmpFile = tmpFile + oneScan.扫描信息.文件名 + ".jpg"; bmp.Save(tmpFile, jpsEncoder, eps); //释放资源 ep.Dispose(); eps.Dispose(); //上传FTP FileInfo fi = new FileInfo(tmpFile); ftpHelper.MakeDirectory(vPath); if (ftpHelper.FileUpLoad(vPath + oneScan.扫描信息.文件名 + ".jpg", fi) == true) { //存入数据库 _scanModel.SaveScanImage(oneScan); } else { return(false); } //ftpHelper.disConnect(); 没有关闭连接的方法吗? } catch (Exception ex) { MsgBox.ShowException(ex, this); } return(true); }
public static void ResizeImage(string FileNameInput, string FileNameOutput, double ResizeHeight, double ResizeWidth, ImageFormat OutputFormat) { using (System.Drawing.Image photo = new Bitmap(FileNameInput)) { double aspectRatio = (double)photo.Width / photo.Height; double boxRatio = ResizeWidth / ResizeHeight; double scaleFactor = 0; if (photo.Width < ResizeWidth && photo.Height < ResizeHeight) { // keep the image the same size since it is already smaller than our max width/height scaleFactor = 1.0; } else { if (boxRatio > aspectRatio) { scaleFactor = ResizeHeight / photo.Height; } else { scaleFactor = ResizeWidth / photo.Width; } } int newWidth = (int)(photo.Width * scaleFactor); int newHeight = (int)(photo.Height * scaleFactor); using (Bitmap bmp = new Bitmap(newWidth, newHeight)) { using (Graphics g = Graphics.FromImage(bmp)) { g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; g.CompositingQuality = CompositingQuality.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(photo, 0, 0, newWidth, newHeight); if (ImageFormat.Png.Equals(OutputFormat)) { bmp.Save(FileNameOutput, OutputFormat); } else if (ImageFormat.Jpeg.Equals(OutputFormat)) { ImageCodecInfo[] info = ImageCodecInfo.GetImageEncoders(); EncoderParameters encoderParameters; using (encoderParameters = new System.Drawing.Imaging.EncoderParameters(1)) { // use jpeg info[1] and set quality to 90 encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L); bmp.Save(FileNameOutput, info[1], encoderParameters); } } } } } }
public static void ResizeImg(int destWidth, int destHeight, string filePath, string saveFilePath) { //重新設定大小 System.Drawing.Image sourImage; WebClient webC = new WebClient(); sourImage = System.Drawing.Image.FromStream(webC.OpenRead(filePath)); sourImage = RotateImage(sourImage); webC.Dispose(); webC = null; int width = 0, height = 0; //按比例縮放 int sourWidth = sourImage.Width; int sourHeight = sourImage.Height; if (sourHeight > destHeight || sourWidth > destWidth) { if ((sourWidth * destHeight) > (sourHeight * destWidth)) { width = destWidth; height = (destWidth * sourHeight) / sourWidth; } else { height = destHeight; width = (sourWidth * destHeight) / sourHeight; } } else { width = sourWidth; height = sourHeight; } Bitmap destBitmap = new Bitmap(width, height); Graphics g = Graphics.FromImage(destBitmap); g.Clear(Color.Transparent); //設置畫布的描繪品質 // g.Clear(Color.Transparent); g.Clear(Color.Black); g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(sourImage, new Rectangle(0, 0, width, height), new Rectangle(0, 0, sourWidth, sourHeight), GraphicsUnit.Pixel); g.Dispose(); //設置壓縮品質 System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(); long[] quality = new long[1]; quality[0] = 100; System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; sourImage.Dispose(); sourImage = null; destBitmap.Save(saveFilePath, System.Drawing.Imaging.ImageFormat.Jpeg); destBitmap.Dispose(); destBitmap = null; }
public static void CompressImage(string fullFilePath, string destinationPath, long compression) { Bitmap bitmap = GetBitmap(fullFilePath); if (bitmap == null) { return; } Bitmap newImage = new Bitmap(bitmap); bool encoderFound = false; System.Drawing.Imaging.ImageCodecInfo encoder = null; var fileName = Path.GetFileName(fullFilePath); if (fileName.ToLower().EndsWith(".jpg") || fileName.ToLower().EndsWith(".jpeg")) { encoderFound = true; encoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); } else if (fileName.ToLower().EndsWith(".bmp")) { encoderFound = true; encoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Bmp); } else if (fileName.ToLower().EndsWith(".tiff")) { encoderFound = true; encoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Tiff); } else if (fileName.ToLower().EndsWith(".gif")) { encoderFound = true; encoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Gif); } else if (fileName.ToLower().EndsWith(".png")) { encoderFound = true; encoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Png); } if (encoderFound) { System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, compression); myEncoderParameters.Param[0] = myEncoderParameter; newImage.Save(System.IO.Path.Combine(destinationPath), encoder, myEncoderParameters); } else { newImage.Save(System.IO.Path.Combine(destinationPath)); } }
public static System.Drawing.Image ZoomImage(System.Drawing.Image bitmap, int destWidth, int destHeight) { //等比縮放 try { System.Drawing.Image sourImage = bitmap; bitmap = RotateImage(bitmap); int width = 0, height = 0; //按比例縮放 int sourWidth = sourImage.Width; int sourHeight = sourImage.Height; if (sourHeight > destHeight || sourWidth > destWidth) { if ((sourWidth * destHeight) > (sourHeight * destWidth)) { width = destWidth; height = (destWidth * sourHeight) / sourWidth; } else { height = destHeight; width = (sourWidth * destHeight) / sourHeight; } } else { width = sourWidth; height = sourHeight; } Bitmap destBitmap = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage(destBitmap); g.Clear(Color.Transparent); //設置畫布的描繪品質 // webpic = Image_ChangeOpacity(webpic, 0f); g.Clear(Color.Transparent); // g.Clear(Color.Black); g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel); //高度置中 //g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height), width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel); //齊底 g.Dispose(); //設置壓縮品質 System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(); long[] quality = new long[1]; quality[0] = 100; System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; sourImage.Dispose(); return(destBitmap); } catch { return(bitmap); } }
//public string pdfToPic(string sourcePdf, string outputPath) public static bool pdfToPic(string pdfInputPath, string outputPath, string imageName, int startPageNum, int endPageNum, ImageFormat imageFormat) { // NOTE: This will only get the first image it finds per page. PdfReader pdf = new PdfReader(pdfInputPath); RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(pdfInputPath); bool flag = true; try { for (int pageNumber = startPageNum; pageNumber <= endPageNum; pageNumber++) { PdfDictionary pg = pdf.GetPageN(pageNumber); // recursively search pages, forms and groups for images. PdfObject obj = FindImageInPDFDictionary(pg); if (obj != null) { int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture)); PdfObject pdfObj = pdf.GetPdfObject(XrefIndex); PdfStream pdfStrem = (PdfStream)pdfObj; byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem); if ((bytes != null)) { using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes)) { memStream.Position = 0; System.Drawing.Image img = System.Drawing.Image.FromStream(memStream); // must save the file while stream is open. if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } //path = Path.Combine(outputPath, String.Format(@"{0}.jpg", pageNumber)); System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1); parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0); System.Drawing.Imaging.ImageCodecInfo jpegEncoder = GetImageEncoder("JPEG"); img.Save(outputPath + imageName + "." + imageFormat.ToString(), jpegEncoder, parms); } } } } } catch (Exception e) { flag = false; } finally { pdf.Close(); raf.Close(); } return(flag); }
public static void SaveJpeg(string path, Image image, long quality) { using (var encoderParameters = new System.Drawing.Imaging.EncoderParameters(1)) using (var encoderParameter = new System.Drawing.Imaging.EncoderParameter(Encoder.Quality, quality)) { ImageCodecInfo codecInfo = ImageCodecInfo.GetImageDecoders().First(codec => codec.FormatID == ImageFormat.Jpeg.Guid); encoderParameters.Param[0] = encoderParameter; image.Save(path, codecInfo, encoderParameters); } }
private void SaveSinglePage(Bitmap bitMap) { ImageCodecInfo codecInfo = getCodecForstring("TIFF"); System.Drawing.Imaging.EncoderParameters iparams = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.Encoder iparam = System.Drawing.Imaging.Encoder.Compression; System.Drawing.Imaging.EncoderParameter iparamPara = new System.Drawing.Imaging.EncoderParameter(iparam, (long)(System.Drawing.Imaging.EncoderValue.CompressionCCITT4)); iparams.Param[0] = iparamPara; bitMap.Save(this.m_FileName, codecInfo, iparams); }
public string Resize(Bitmap bmp, string strFileThumb, int P_Width) { string thumbnailFilePath = string.Empty; string FileName = string.Empty; try { float ratio = (float)bmp.Width / bmp.Height; int imgHeight = 0; //System.Drawing.Image img = Crop(bmp, P_Width, (int)(P_Width * ratio), AnchorPosition.Center); // int iz = HttpContext.Current.Request.QueryString["iz"] != null ? Convert.ToInt32(HttpContext.Current.Request.QueryString["iz"]) : 0; //switch (iz) { //case 0 : // //3x4 // imgHeight = Convert.ToInt32( 0.75 * P_Width); // break; //case 1: // //16x9 // imgHeight = Convert.ToInt32((float)9 / 16 * P_Width); // break; // default: // normal: imgHeight = Convert.ToInt32(P_Width / ratio); // break; } imgHeight = Convert.ToInt32((float)9 / 16 * P_Width); System.Drawing.Image img = Crop(bmp, P_Width + 1, imgHeight + 1, AnchorPosition.Center); using (Bitmap thumb = new Bitmap(img)) { //thumb.SetResolution(P_Width, P_Width); using (Graphics g = Graphics.FromImage(thumb)) // Create Graphics object from original Image { g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; //Set Image codec of JPEG type, the index of JPEG codec is "1" System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1]; //Set the parameters for defining the quality of the thumbnail... here it is set to 100% System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1); eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 92L); //Now draw the image on the instance of thumbnail Bitmap object g.DrawImage(thumb, new Rectangle(0, 0, thumb.Width, thumb.Height)); thumb.Save(strFileThumb, codec, eParams); } } } catch (Exception ex) { throw ex; } return(FileName); }
public static void ExtractImagesFromPDF(string sourcePdf, string outputPath) { // NOTE: This will only get the first image it finds per page. PdfReader pdf = new PdfReader(sourcePdf); //RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf); try { for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++) { PdfDictionary pg = pdf.GetPageN(pageNumber); // recursively search pages, forms and groups for images. PdfObject obj = FindImageInPDFDictionary(pg); if (obj != null) { int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture)); PdfObject pdfObj = pdf.GetPdfObject(XrefIndex); PdfStream pdfStrem = (PdfStream)pdfObj; byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem); if ((bytes != null)) { using (System.IO.MemoryStream memStream = new System.IO.MemoryStream(bytes)) { memStream.Position = 0; System.Drawing.Image img = ImageHelper.ResizeImage(System.Drawing.Image.FromStream(memStream), .33M); // must save the file while stream is open. if (!Directory.Exists(outputPath)) { Directory.CreateDirectory(outputPath); } string path = Path.Combine(outputPath, String.Format(@"{0}.jpg", pageNumber)); System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1); parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0); var encoders = ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.ImageCodecInfo jpegEncoder = encoders.FirstOrDefault(p => p.CodecName == "Built-in JPEG Codec"); img.Save(path, jpegEncoder, parms); } } } } } catch { throw; } finally { pdf.Close(); //raf.Close(); } }
// Расшифровка QR-кода private int QRCodeDecode(iTextSharp.text.Image QR) { PdfReader pdf = new PdfReader(InputFilePath); PdfDictionary pg = pdf.GetPageN(1); PdfDictionary res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES)); PdfDictionary xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT)); if (xobj == null) { return(0); } foreach (PdfName name in xobj.Keys) { PdfObject obj = xobj.Get(name); if (!obj.IsIndirect()) { continue; } PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj); PdfName type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE)); if (!type.Equals(PdfName.IMAGE)) { continue; } int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture)); PdfObject pdfObj = pdf.GetPdfObject(XrefIndex); PdfStream pdfStrem = (PdfStream)pdfObj; byte[] bytes = PdfReader.GetStreamBytesRaw((PRStream)pdfStrem); if (bytes == null) { continue; } ; //memStream.Position = 0; //System.Drawing.Image img = System.Drawing.Image.FromStream(memStream); } string path = Path.Combine(String.Format(@"result-{0}.jpg", 1)); System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1); parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0); var jpegEncoder = ImageCodecInfo.GetImageEncoders().ToList().Find(x => x.FormatID == ImageFormat.Jpeg.Guid); //img.Save(path, jpegEncoder, parms); return(0); }
/// <summary>Saves image to a file</summary> /// <param name="bmp">Bitmap to save</param> /// <param name="FileName">File name</param> /// <param name="Quality">Image quality, from 0 to 100. 97 should do fine</param> public static void Save(Bitmap bmp, string FileName, int Quality) { Int64 quality = (Int64)Quality; System.Drawing.Imaging.Encoder Encoder = System.Drawing.Imaging.Encoder.Quality; System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(Encoder, quality); myEncoderParameters.Param[0] = myEncoderParameter; System.Drawing.Imaging.ImageCodecInfo jgpEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); bmp.Save(FileName, jgpEncoder, myEncoderParameters); }
private Bitmap ZoomImage(Bitmap bitmap, int destHeight, int destWidth) { try { System.Drawing.Image sourImage = bitmap; int width = 0, height = 0; //按比例缩放 int sourWidth = sourImage.Width; int sourHeight = sourImage.Height; if (sourHeight > destHeight || sourWidth > destWidth) { if ((sourWidth * destHeight) > (sourHeight * destWidth)) { width = destWidth; height = (destWidth * sourHeight) / sourWidth; } else { height = destHeight; width = (sourWidth * destHeight) / sourHeight; } } else { width = sourWidth; height = sourHeight; } Bitmap destBitmap = new Bitmap(destWidth, destHeight); Graphics g = Graphics.FromImage(destBitmap); g.Clear(Color.Transparent); //设置画布的描绘质量 g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(sourImage, new Rectangle((destWidth - width) / 2, (destHeight - height) / 2, width, height), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Pixel); g.Dispose(); //设置压缩质量 System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(); long[] quality = new long[1]; quality[0] = 100; System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; sourImage.Dispose(); bitmap.Dispose(); sourImage.Dispose(); return(destBitmap); } catch { return(bitmap); } }
private static string ConvertJpgToPng(int i, ImageRenderListener listener, string diretorio) { System.Drawing.Imaging.EncoderParameters parms = new System.Drawing.Imaging.EncoderParameters(1); parms.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 0); System.Drawing.Imaging.ImageCodecInfo jpegEncoder = ImageCodecInfo.GetImageEncoders().Single(p => p.CodecName.Contains("PNG")); System.Drawing.Image img = System.Drawing.Image.FromStream(new MemoryStream(listener.Images[i])); string path = diretorio + "\\" + i + listener.ImageNames[i].ToLower().Replace(".jpg", ".png"); img.Save(path, jpegEncoder, parms); return(path); }
public static bool ImgResize(string Path, int Width, int Height, System.IO.Stream StreamFileupload, long ImgQuality) { try { //Thumbnain yaradaq, şəkil təmizliyi maksimum olacaq. *************************** string thumbnailFilePath = string.Empty; using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(StreamFileupload)) { if (Width == -1) { Width = (bmp.Width * (Height * 100) / bmp.Height) / 100; } else if (Height == -1) { Height = (bmp.Height * (Width * 100) / bmp.Width) / 100; } thumbnailFilePath = HttpContext.Current.Server.MapPath(Path); //Save File System.Drawing.Size newSize = new System.Drawing.Size(Width, Height); // Thumbnail ölçüsü (width = xxx) (height = xxx) using (System.Drawing.Bitmap thumb = new System.Drawing.Bitmap(bmp, newSize)) { using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(thumb)) // Original şəkili grafikə çeviririk: Təmizləmək üçün { //Təmizlik paramterləri: g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; //Şəkil Codec yaradırıq. Sondakı 1 index dəyəridir. System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1]; //Encoding paramter maksimum 100L gedir o zaman şəkilin həcmi çox olur. System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1); eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImgQuality); //Şəkili yaradırıq və dəyərlərini üstəki kimi daxil edirik. g.DrawImage(bmp, new System.Drawing.Rectangle(0, 0, thumb.Width, thumb.Height)); //Son olaraq Save edirik: thumb.Save(thumbnailFilePath, codec, eParams); return(true); } } } } catch (Exception er) { DALCL.ErrorLog(string.Format("ImgResize catch error: {0}, path: {1}", er.Message, Path)); return(false); } }
/// <summary> /// 添加图片水印 /// </summary> /// <param name="oldpath">原图片绝对地址</param> /// <param name="newpath">新图片放置的绝对地址</param> public void addWaterMark(string oldpath, string newpath) { try { System.Drawing.Image image = System.Drawing.Image.FromFile(oldpath); Bitmap b = new Bitmap(image.Width, image.Height, PixelFormat.Format24bppRgb); Graphics g = Graphics.FromImage(b); g.Clear(Color.White); g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.High; g.DrawImage(image, 0, 0, image.Width, image.Height); if (IsWaterMark) { switch (this.WMType) { case WaterMarkType.WM_IMAGE: //水印图片 this.addWatermarkImage(g, _waterMarkImgPath, WMLocation, image.Width, image.Height); break; case WaterMarkType.WM_TEXT: //水印文字 this.addWatermarkText(g, this.WaterMarkText, WMLocation, image.Width, image.Height); break; } #region 降低图片质量 System.Drawing.Imaging.ImageCodecInfo encoder = GetEncoderInfo("image/jpeg"); System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1); encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)80); #endregion b.Save(newpath, encoder, encoderParams); encoderParams.Dispose(); b.Dispose(); image.Dispose(); } } catch { if (File.Exists(oldpath)) { File.Delete(oldpath); } } finally { if (File.Exists(oldpath)) { File.Delete(oldpath); } } }
static public byte[] toByte(this Mat mat) { ImageCodecInfo bmpEncoder = ImageCodecInfo.GetImageEncoders().Single(x => x.FormatDescription == "BMP"); System.Drawing.Imaging.Encoder encoder2 = System.Drawing.Imaging.Encoder.Quality; EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters(1); EncoderParameter parameter = new EncoderParameter(encoder2, 50L); parameters.Param[0] = parameter; System.IO.Stream stream = new MemoryStream(); mat.Bitmap.Save(stream, bmpEncoder, parameters); byte[] bytes = ((MemoryStream)stream).ToArray(); return bytes; }
public static void Resize_Picture(ref Bitmap bmp, string Des, int FinalWidth, int FinalHeight, int ImageQuality) { System.Drawing.Bitmap NewBMP; System.Drawing.Graphics graphicTemp; int iWidth; int iHeight; if ((FinalHeight == 0) && (FinalWidth != 0)) { iWidth = FinalWidth; iHeight = (bmp.Size.Height * iWidth / bmp.Size.Width); } else if ((FinalHeight != 0) && (FinalWidth == 0)) { iHeight = FinalHeight; iWidth = (bmp.Size.Width * iHeight / bmp.Size.Height); } else { iWidth = FinalWidth; iHeight = FinalHeight; } NewBMP = new System.Drawing.Bitmap(iWidth, iHeight); graphicTemp = System.Drawing.Graphics.FromImage(NewBMP); graphicTemp.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; graphicTemp.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphicTemp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphicTemp.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphicTemp.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphicTemp.DrawImage(bmp, 0, 0, iWidth, iHeight); graphicTemp.Dispose(); System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(); System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, ImageQuality); encoderParams.Param[0] = encoderParam; System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); //for (int fwd = 0; fwd <= arrayICI.Length - 1; fwd++) //{ // if (arrayICI[fwd].FormatDescription.Equals("JPEG")) // { // NewBMP.Save(, arrayICI[fwd], encoderParams); // } //} bmp = NewBMP; //NewBMP.Dispose(); //bmp.Dispose(); }
private void SaveImage_Jpg(Stream stream, System.Drawing.Image image) { var myEncoder = System.Drawing.Imaging.Encoder.Quality; var cInfo = GetEncoderInfo("image/jpeg"); using (var p1 = new System.Drawing.Imaging.EncoderParameters(1)) { using (var p2 = new EncoderParameter(myEncoder, PluginSettings.JpgImageQuality)) { p1.Param[0] = p2; image.Save(stream, cInfo, p1); } } }