public void SaveBmpWithImageCodecInfo(System.Drawing.Image img, string photoPath) { System.Drawing.Imaging.ImageCodecInfo encoderInfo = PictureWaterMark.GetEncoderInfo("image/jpeg"); System.Drawing.Imaging.Encoder quality = System.Drawing.Imaging.Encoder.Quality; System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(quality, 100L); encoderParameters.Param[0] = encoderParameter; if (img == null) { return; } System.Drawing.Bitmap bitmap = null; try { bitmap = new System.Drawing.Bitmap(img); bitmap.Save(photoPath, encoderInfo, encoderParameters); } catch (Exception ex) { Log.WriteLog("SaveBmpWithImageCodecInfo出错", ex); } finally { bitmap.Dispose(); } }
private static Bitmap ZoomImage(Bitmap sourImage, int destWidth) { try { Bitmap destBitmap = new Bitmap(destWidth, 50); Graphics g = Graphics.FromImage(destBitmap); g.Clear(Color.Transparent); //设置画布的描绘质量 g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.AssumeLinear; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; g.DrawImage(sourImage, new Rectangle(0, 0, destWidth, 50), 0, 0, sourImage.Width, sourImage.Height, GraphicsUnit.Point); 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(sourImage); } }
/// <summary> /// Initializes a new instance of the <see cref="T:Common.Drawing.Imaging.EncoderParameter" /> class with the /// specified <see cref="T:Common.Drawing.Imaging.Encoder" /> object and four arrays of 32-bit integers. The four /// arrays represent an array rational ranges. A rational range is the set of all fractions from a minimum fractional /// value through a maximum fractional value. Sets the /// <see cref="P:Common.Drawing.Imaging.EncoderParameter.ValueType" /> property to /// <see cref="F:Common.Drawing.Imaging.EncoderParameterValueType.ValueTypeRationalRange" />, and sets the /// <see cref="P:Common.Drawing.Imaging.EncoderParameter.NumberOfValues" /> property to the number of elements in the /// <paramref name="numerator1" /> array, which must be the same as the number of elements in the other three arrays. /// </summary> /// <param name="encoder"> /// An <see cref="T:Common.Drawing.Imaging.Encoder" /> object that encapsulates the globally unique /// identifier of the parameter category. /// </param> /// <param name="numerator1"> /// An array of 32-bit integers that specifies the numerators of the minimum values for the /// ranges. The integers in the array must be nonnegative. /// </param> /// <param name="denominator1"> /// An array of 32-bit integers that specifies the denominators of the minimum values for the /// ranges. The integers in the array must be nonnegative. /// </param> /// <param name="numerator2"> /// An array of 32-bit integers that specifies the numerators of the maximum values for the /// ranges. The integers in the array must be nonnegative. /// </param> /// <param name="denominator2"> /// An array of 32-bit integers that specifies the denominators of the maximum values for the /// ranges. The integers in the array must be nonnegative. /// </param> public EncoderParameter(Encoder encoder, int[] numerator1, int[] denominator1, int[] numerator2, int[] denominator2) { WrappedEncoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, numerator1, denominator1, numerator2, denominator2); }
/// <summary> /// 儲存圖片 /// </summary> void func_SaveBitmap(System.Drawing.Bitmap b, String type, string path) { //png if (type == "png") { b.Save(path); return; } //------------ //jpg var jpgEncoder = GetEncoder(System.Drawing.Imaging.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. var myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); var myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 98L); myEncoderParameters.Param[0] = myEncoderParameter; b.Save(path, jpgEncoder, myEncoderParameters); }
public static System.Drawing.Imaging.EncoderParameters GetQualityParameters(long ImageQuality) { 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 = new System.Drawing.Imaging.EncoderParameter[] { encoderParam }; return(encoderParams); }
public virtual void saveJPEG(System.String filename) { try { // Set the quality to 100 (must be a long) System.Drawing.Imaging.Encoder qualityEncoder = System.Drawing.Imaging.Encoder.Quality; System.Drawing.Imaging.EncoderParameter ratio = new System.Drawing.Imaging.EncoderParameter(qualityEncoder, 100L); // Add the quality parameter to the list System.Drawing.Imaging.EncoderParameters codecParams = new System.Drawing.Imaging.EncoderParameters(1); codecParams.Param[0] = ratio; // Get Codec Info using MIME type System.Drawing.Imaging.ImageCodecInfo JpegCodecInfo = GetEncoderInfo("image/jpeg"); // System.Console.Out.WriteLine("Saving '" + filename + "'."); offImg.Save(filename, JpegCodecInfo, codecParams); System.Console.Out.WriteLine("JPEG image saved."); } catch (System.Exception e) { System.Console.Out.WriteLine(e); } }
/// <summary> /// JPGファイルに変換 /// </summary> /// <param name="pngPath">元のPNGファイルフルパス</param> /// <param name="quality">品質(0-100)</param> /// <returns></returns> static string ConvertToJpeg(string pngPath, int quality) { string jpgPath = null; using (Bitmap bmp = new Bitmap(pngPath)) { try { string ext = System.IO.Path.GetExtension(pngPath); jpgPath = pngPath.Replace(ext, "") + ".jpg"; System.Drawing.Imaging.EncoderParameters eps = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.EncoderParameter ep = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); eps.Param[0] = ep; System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg"); bmp.Save(jpgPath, ici, eps); } catch (Exception ex) { throw ex; } bmp.Dispose(); } return(jpgPath); }
public static void SaveImage(string fileName, int quality) { //画像ファイルを読み込む System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(fileName); //EncoderParameterオブジェクトを1つ格納できる //EncoderParametersクラスの新しいインスタンスを初期化 //ここでは品質のみ指定するため1つだけ用意する System.Drawing.Imaging.EncoderParameters eps = new System.Drawing.Imaging.EncoderParameters(1); //品質を指定 System.Drawing.Imaging.EncoderParameter ep = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); //EncoderParametersにセットする eps.Param[0] = ep; //イメージエンコーダに関する情報を取得する System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg"); //新しいファイルの拡張子を取得する string ext = ici.FilenameExtension.Split(';')[0]; ext = System.IO.Path.GetExtension(ext).ToLower(); //保存するファイル名を決定(拡張子を変える) string saveName = System.IO.Path.ChangeExtension(fileName, ext); //保存する bmp.Save(saveName, ici, eps); bmp.Dispose(); eps.Dispose(); }
private static System.Drawing.Imaging.EncoderParameters getOptiumQuarity(long size, System.Drawing.Bitmap bmp, System.Drawing.Imaging.ImageCodecInfo ici) { long quality = 100; //EncoderParameterオブジェクトを1つ格納できる //EncoderParametersクラスの新しいインスタンスを初期化 //ここでは品質のみ指定するため1つだけ用意する System.Drawing.Imaging.EncoderParameters eps = new System.Drawing.Imaging.EncoderParameters(1); System.IO.MemoryStream sr = new System.IO.MemoryStream(); do { sr.Flush();//Streamの中身をクリア sr = new System.IO.MemoryStream(); //品質を指定 System.Drawing.Imaging.EncoderParameter ep = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.Quality, (long)quality); //EncoderParametersにセットする eps.Param[0] = ep; //試しに保存する bmp.Save(sr, ici, eps); quality -= 5; } while (sr.Length > size); return(eps); }
/**/ /// <param name="fileName">图像名</param> /// <param name="quality">品质</param> public static void SaveImage(string fileName, int quality) { Bitmap myBitmap = new Bitmap(fileName); System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.Quality, quality); myEncoderParameters.Param[0] = myEncoderParameter; System.Drawing.Imaging.ImageCodecInfo myImageCodecInfo; myImageCodecInfo = GetEncoderInfo("image/jpeg"); string ext = myImageCodecInfo.FilenameExtension.Split(';')[0]; ext = System.IO.Path.GetExtension(ext).ToLower(); string saveName = System.IO.Path.ChangeExtension(fileName, ext); //保存 myBitmap.Save(saveName, myImageCodecInfo, myEncoderParameters); }
private void buttonSavePicture_Click(object sender, EventArgs e) { if (pictureBoxHierarchy.Image != null) { SaveFileDialog savedialog = new SaveFileDialog(); savedialog.Title = "Сохранить картинку как..."; savedialog.OverwritePrompt = true; savedialog.CheckPathExists = true; savedialog.Filter = "Image Files(*.JPG)|*.JPG"; savedialog.ShowHelp = true; System.Drawing.Imaging.ImageCodecInfo jpgEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); 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, 100L); myEncoderParameters.Param[0] = myEncoderParameter; if (savedialog.ShowDialog() == DialogResult.OK) { try { pictureBoxHierarchy.Image.Save(savedialog.FileName, jpgEncoder, myEncoderParameters); } catch { MessageBox.Show("Невозможно сохранить изображение", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
/// <summary> /// Initializes a new instance of the <see cref="ThumbnailCreator"/> class. /// </summary> /// <param name="tnSettings">The <see cref="ThumbnailSettings"/> to use.</param> /// <param name="worker">The <see cref="System.ComponentModel.BackgroundWorker"/>worker to use. /// </param> public ThumbnailCreator(ThumbnailSettings tnSettings, System.ComponentModel.BackgroundWorker worker) { this._tnSettings = tnSettings; this._worker = worker; #if false _imageCodec = GetEncoder (System.Drawing.Imaging.ImageFormat.Png); _qualityParameter = new System.Drawing.Imaging.EncoderParameter ( System.Drawing.Imaging.Encoder.Quality, 75L); _qualityParameters = new System.Drawing.Imaging.EncoderParameters (1); _qualityParameters.Param[0] = _qualityParameter; #else _imageCodec = GetEncoder (System.Drawing.Imaging.ImageFormat.Jpeg); _qualityParameter = new System.Drawing.Imaging.EncoderParameter ( System.Drawing.Imaging.Encoder.Quality, 75L); _qualityParameters = new System.Drawing.Imaging.EncoderParameters (1); _qualityParameters.Param[0] = _qualityParameter; #endif #if false using (System.Drawing.Bitmap bitmap1 = new System.Drawing.Bitmap (1, 1)) { System.Drawing.Imaging.EncoderParameters paramList = bitmap1.GetEncoderParameterList (_imageCodec.Clsid); System.Drawing.Imaging.EncoderParameter[] encParams = paramList.Param; foreach (System.Drawing.Imaging.EncoderParameter p in encParams) { THelper.Information ("Type {0}, GUID {1}", p.ValueType, p.Encoder.Guid); } paramList.Dispose (); } #endif }
public static void SaveImage(System.Drawing.Image Image, string Destination) { System.Drawing.Imaging.ImageCodecInfo jgpEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); 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, (long)Settings.ImageQuality); myEncoderParameters.Param[0] = myEncoderParameter; Image.Save(Destination, jgpEncoder, myEncoderParameters); }
public static MemoryStream CreateImageForDB(Stream sFile, int intHeight, int intWidth) { var newStream = new MemoryStream(); var g = Image.FromStream(sFile); //Dim thisFormat = g.RawFormat if (intHeight > 0 & intWidth > 0) { int newHeight; int newWidth; newHeight = intHeight; newWidth = intWidth; Size imgSize; if (g.Width > newWidth | g.Height > newHeight) { imgSize = NewImageSize(g.Width, g.Height, newWidth, newHeight); imgHeight = imgSize.Height; imgWidth = imgSize.Width; } else { imgHeight = g.Height; imgWidth = g.Width; } } else { imgWidth = g.Width; imgHeight = g.Height; } var imgOutput1 = new Bitmap(g, imgWidth, imgHeight); Graphics bmpOutput = Graphics.FromImage(imgOutput1); bmpOutput.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; bmpOutput.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; var compressionRectange = new Rectangle(0, 0, imgWidth, imgHeight); bmpOutput.DrawImage(g, compressionRectange); System.Drawing.Imaging.ImageCodecInfo myImageCodecInfo; System.Drawing.Imaging.Encoder myEncoder; System.Drawing.Imaging.EncoderParameter myEncoderParameter; System.Drawing.Imaging.EncoderParameters myEncoderParameters; myImageCodecInfo = GetEncoderInfo("image/jpeg"); myEncoder = System.Drawing.Imaging.Encoder.Quality; myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 90); myEncoderParameters.Param[0] = myEncoderParameter; imgOutput1.Save(newStream, myImageCodecInfo, myEncoderParameters); g.Dispose(); imgOutput1.Dispose(); bmpOutput.Dispose(); return(newStream); }
/// <summary> /// 等比例缩放图片 /// </summary> /// <param name="bitmap"></param> /// <param name="destHeight"></param> /// <param name="destWidth"></param> /// <returns></returns> private Bitmap ZoomImage(Bitmap bitmap, int destWidth, int destHeight) { try { 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 = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = 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(12, 0, 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 static void ImageQualityLevel() { var bitmap = new System.Drawing.Bitmap(@"C:\Good Dainasoor.jpg"); var imageEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); var encoderType = System.Drawing.Imaging.Encoder.Quality; var encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); var imageQuality = 50L; var parameter = new System.Drawing.Imaging.EncoderParameter(encoderType, imageQuality); encoderParameters.Param[0] = parameter; bitmap.Save(@"C:\Good Dainasoor.jpg", imageEncoder, encoderParameters); bitmap.Dispose(); }
public static bool Resize_Picture(string Org, string Des, int FinalWidth, int FinalHeight, int ImageQuality) { System.Drawing.Bitmap NewBMP; System.Drawing.Graphics graphicTemp; System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(Org); 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(Des, arrayICI[fwd], encoderParams); } } NewBMP.Dispose(); bmp.Dispose(); return(true); }
/// <summary> /// ����ͼƬ�ļ� /// </summary> /// <param name="fileName">ͼƬ�ļ���</param> public static void CreateImage(string fileName) { int width = 1; int height = 0; int constWidth = 100; FileInfo fi = new FileInfo(fileName); File.Copy(fileName, HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["FCKeditor:TempUploadPicPath"] + fi.Name), true); Bitmap myBitmap = new Bitmap(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["FCKeditor:TempUploadPicPath"] + fi.Name)); if (myBitmap.Width > constWidth) { width = constWidth; height = (int)(myBitmap.Height * width / myBitmap.Width); } else { width = myBitmap.Width; height = myBitmap.Height; } //Configure JPEG Compression Engine System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(); long[] quality = new long[1]; quality[0] = 75; System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.ImageCodecInfo jpegICI = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICI = arrayICI[x]; break; } } System.Drawing.Image myThumbnail = CreateThumbnail(myBitmap, width, height, false); myThumbnail.Save(fileName, jpegICI, encoderParams); myThumbnail.Dispose(); myBitmap.Dispose(); File.Delete(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["FCKeditor:TempUploadPicPath"] + fi.Name)); }
public static void SaveAsJpeg(Bitmap bmp, string path, int quality) { //EncoderParameterオブジェクトを1つ格納できる //EncoderParametersクラスの新しいインスタンスを初期化 //ここでは品質のみ指定するため1つだけ用意する System.Drawing.Imaging.EncoderParameters eps = new System.Drawing.Imaging.EncoderParameters(1); //品質を指定 System.Drawing.Imaging.EncoderParameter ep = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality); //EncoderParametersにセットする eps.Param[0] = ep; //イメージエンコーダに関する情報を取得する System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg"); //保存する bmp.Save(path, ici, eps); eps.Dispose(); }
public static System.Drawing.Bitmap ResizeImage(string fromFile, int maxWidth, int maxHeight, int quality = 100) { System.Drawing.Bitmap image = new System.Drawing.Bitmap(fromFile); // 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. System.Drawing.Bitmap newImage = new System.Drawing.Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb); // Draws the image in the specified size with quality mode set to HighQuality using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(newImage)) { graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.DrawImage(image, 0, 0, newWidth, newHeight); } // Get an ImageCodecInfo object that represents the JPEG codec. System.Drawing.Imaging.ImageCodecInfo imageCodecInfo = ImageUtils.GetEncoderInfo(System.Drawing.Imaging.ImageFormat.Jpeg); // Create an Encoder object for the Quality parameter. System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality; // Create an EncoderParameters object. System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); // Save the image as a JPEG file with quality level. System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, quality); encoderParameters.Param[0] = encoderParameter; // newImage.Save(SavefilePath, imageCodecInfo, encoderParameters); return newImage; }
public static void SaveThumbnail(Bitmap bit, Size size, string targePath) { System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(); long[] quality = new long[1]; quality[0] = 75; System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.ImageCodecInfo jpegICI = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICI = arrayICI[x]; break; } } var image = Thumbnail(bit, size); image.Save(targePath, jpegICI, encoderParams); }
public static void CreateThumbnailImage(string ImagePath, string ThumbnailPath, int Width, int Height, int RateX, int RateY, long ImageQuality) { Bitmap bmp1, bmp2; 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 = new System.Drawing.Imaging.EncoderParameter[] { encoderParam }; if (!File.Exists(ThumbnailPath)) { if (File.Exists(ImagePath)) { bmp1 = new Bitmap(ImagePath); bmp2 = new Bitmap(bmp1.GetThumbnailImage((int)((decimal)bmp1.Width / ((decimal)bmp1.Height / (decimal)Height)), Height, null, IntPtr.Zero)); bmp1.Dispose(); bmp1 = Justify(bmp2, RateX, RateY); bmp2.Dispose(); try { if (ImageQuality > 0) { bmp1.Save(ThumbnailPath, GetImageEncoder(ThumbnailPath), encoderParams); } else { bmp1.Save(ThumbnailPath); } } catch (Exception ex) { throw ex; } finally { bmp1.Dispose(); } } } }
/// <summary> /// 压缩图片处理 /// </summary> /// <param name="stream">图片流</param> /// <param name="quality">质量 取值 0-100之间,数值越大质量越高</param> public Byte[] CompressionImageProcessing(Stream stream, long quality = 0L) { using (System.Drawing.Image img = System.Drawing.Image.FromStream(stream)) { using (System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(img)) { System.Drawing.Imaging.ImageCodecInfo codecInfo = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.FormatID == img.RawFormat.Guid); System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality; System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, quality); encoderParameters.Param[0] = encoderParameter; using (System.IO.MemoryStream ms = new MemoryStream()) { bitmap.Save(ms, codecInfo, encoderParameters); encoderParameters.Dispose(); encoderParameter.Dispose(); return(ms.ToArray()); } } } }
public Byte[] SetImgToByte(string imgPath) { using (MemoryStream ms = new MemoryStream()) { using (Bitmap bm = new Bitmap(this.pictureBox1.Image)) { System.Drawing.Imaging.EncoderParameters encoderP = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.EncoderParameter p = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 8); encoderP.Param[0] = p; System.Drawing.Imaging.ImageCodecInfo[] CodecInfo = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); var c = CodecInfo.Where(r => r.MimeType == "image/jpeg").FirstOrDefault(); bm.Save(ms, c, encoderP); } ms.Position = 0; Byte[] byteData = new Byte[ms.Length]; ms.Read(byteData, 0, byteData.Length); ms.Close(); return(byteData); } }
/* bmp = image/bmp gif = image/gif jpg = image/jpeg (image/pjpeg) jpeg = image/jpeg (image/pjpeg) png = image/png (image/x-png) tiff = image/tiff */ public void test() { System.IO.FileStream stream = System.IO.File.Create("test.jpg"); // Initialize the bytes array with the stream length and then fill it with data // byte[] bytesInStream = new byte[stream.Length]; // stream.Read(bytesInStream, 0, (int)bytesInStream.Length); // // Use write method to write to the specified file // fileStream.Write(bytesInStream, 0, (int) bytesInStream.Length); System.Drawing.Imaging.ImageCodecInfo jgpEncoder = GetEncoder(System.Drawing.Imaging.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. System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 95L); myEncoderParameters.Param[0] = myEncoderParameter; // System.IO.Stream stream1 = new System.IO.MemoryStream(); System.Drawing.Image image1 = System.Drawing.Image.FromFile(@"test.png"); image1.Save(stream, jgpEncoder, myEncoderParameters); }
/// <summary> /// 加图片水印 /// </summary> /// <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 Path, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency) { System.Drawing.Image img = System.Drawing.Image.FromFile(Path); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(img); //设置高质量插值法 //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; System.Drawing.Image watermark = new System.Drawing.Bitmap(watermarkFilename); if (watermark.Height >= img.Height || watermark.Width >= img.Width) { return; } System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes(); System.Drawing.Imaging.ColorMap colorMap = new System.Drawing.Imaging.ColorMap(); colorMap.OldColor = System.Drawing.Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = System.Drawing.Color.FromArgb(0, 0, 0, 0); System.Drawing.Imaging.ColorMap[] remapTable = { colorMap }; imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.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 } }; System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.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 System.Drawing.Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, System.Drawing.GraphicsUnit.Pixel, imageAttributes); System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.ImageCodecInfo ici = null; foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs) { //if (codec.MimeType.IndexOf("jpeg") > -1) if (codec.MimeType.Contains("jpeg")) { ici = codec; } } System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) { quality = 80; } qualityParam[0] = quality; System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.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(); }
static int Main(string[] args) { string gmlSource = String.Empty; string cacheSource = String.Empty; string cacheTarget = String.Empty; int jpegQuality = -1, maxlevel = -1; bool listFilenames = false; for (int i = 0; i < args.Length - 1; i++) { if (args[i] == "-gml") { gmlSource = args[++i]; } if (args[i] == "-cache") { cacheSource = args[++i]; } else if (args[i] == "-target") { cacheTarget = args[++i]; } else if (args[i] == "-jpeg-qual") { jpegQuality = int.Parse(args[++i]); } else if (args[i] == "-maxlevel") { maxlevel = int.Parse(args[++i]); } else if (args[i] == "-listfilenames") { listFilenames = true; } } if (String.IsNullOrWhiteSpace(gmlSource) || String.IsNullOrWhiteSpace(cacheSource) || String.IsNullOrWhiteSpace(cacheTarget)) { Console.WriteLine("USAGE:"); Console.WriteLine("gView.Cmd.ClipCompactTilecache.exe -gml <Filename> -cache <cachedirectory> -target <cachetarget>"); Console.WriteLine(" [-jpeg-qual <quality 0..100>] -maxlevel <level>"); Console.WriteLine(" [-listfilenames]"); return(1); } PlugInManager compMan = new PlugInManager(); IFeatureDataset gmlDataset = compMan.CreateInstance(new Guid("dbabe7f1-fe46-4731-ab2b-8a324c60554e")) as IFeatureDataset; gmlDataset.ConnectionString = gmlSource; gmlDataset.Open(); List <IPolygon> sourcePolygons = new List <IPolygon>(); foreach (var element in gmlDataset.Elements) { if (element.Class is IFeatureClass) { var fc = (IFeatureClass)element.Class; using (var cursor = fc.GetFeatures(null)) { IFeature feature; while ((feature = cursor.NextFeature) != null) { if (feature.Shape is IPolygon) { sourcePolygons.Add((IPolygon)feature.Shape); } } } } } if (!listFilenames) { Console.WriteLine(sourcePolygons.Count + " polygons found for clipping..."); } FileInfo configFile = new FileInfo(cacheSource + @"\conf.json"); if (!configFile.Exists) { throw new ArgumentException("File " + configFile.FullName + " not exists"); } #region Image Encoding Parameters System.Drawing.Imaging.ImageCodecInfo jpgEncoder = GetEncoder(System.Drawing.Imaging.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. System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); #endregion CompactTileConfig cacheConfig = JsonConvert.DeserializeObject <CompactTileConfig>(File.ReadAllText(configFile.FullName)); double dpm = cacheConfig.Dpi / 0.0254; foreach (var level in cacheConfig.Levels) { if (!listFilenames) { Console.WriteLine("Level: " + level.Level + " Scale=" + level.Scale); } double resolution = (level.Scale / dpm); double tileWorldWidth = cacheConfig.TileSize[0] * resolution; double tileWorldHeight = cacheConfig.TileSize[1] * resolution; var scaleDirectory = new DirectoryInfo(cacheSource + @"\" + ((int)level.Scale).ToString()); if (!scaleDirectory.Exists) { continue; } foreach (var bundleFile in scaleDirectory.GetFiles("*.tilebundle")) { var bundle = new Bundle(bundleFile.FullName); if (!bundle.Index.Exists) { continue; } int startRow = bundle.StartRow, startCol = bundle.StartCol; double bundleWorldWidth = tileWorldWidth * 128D, bundleWorldHeight = tileWorldHeight * 128D; IPoint bundleLowerLeft = new Point(cacheConfig.Origin[0] + startCol * tileWorldWidth, cacheConfig.Origin[1] - startRow * tileWorldHeight - bundleWorldHeight); IEnvelope bundleEnvelope = new Envelope(bundleLowerLeft, new Point(bundleLowerLeft.X + bundleWorldWidth, bundleLowerLeft.Y + bundleWorldHeight)); if (!Intersect(bundleEnvelope, sourcePolygons)) { continue; } if (listFilenames) { Console.WriteLine(bundleFile.FullName); continue; } Console.WriteLine("Clip bundle: " + bundleFile.FullName); var clippedBundleFile = new FileInfo(cacheTarget + @"\" + (int)level.Scale + @"\" + bundleFile.Name); if (!clippedBundleFile.Directory.Exists) { clippedBundleFile.Directory.Create(); } if (clippedBundleFile.Exists) { clippedBundleFile.Delete(); } var indexBuilder = new CompactTilesIndexBuilder(); int clippedTilePos = 0; for (int r = 0; r < 128; r++) { for (int c = 0; c < 128; c++) { int tileLength; int tilePos = bundle.Index.TilePosition(r, c, out tileLength); if (tilePos >= 0 && tileLength >= 0) { IPoint tileLowerLeft = new Point(cacheConfig.Origin[0] + (startCol + c) * tileWorldWidth, cacheConfig.Origin[1] - (startRow + r + 1) * tileWorldHeight); IEnvelope tileEnvelope = new Envelope(tileLowerLeft, new Point(tileLowerLeft.X + tileWorldWidth, tileLowerLeft.Y + tileWorldHeight)); if (!Intersect(tileEnvelope, sourcePolygons)) { continue; } Console.WriteLine("Append tile " + level.Level + "/" + (startRow + r) + "/" + (startCol + c)); byte[] data = bundle.ImageData(tilePos, tileLength); if (jpegQuality > 0) { #region New Jpeg Quality MemoryStream ms = new MemoryStream(data); using (System.Drawing.Image image = System.Drawing.Image.FromStream(ms)) { MemoryStream outputMs = new MemoryStream(); System.Drawing.Imaging.EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, Convert.ToInt64(jpegQuality)); myEncoderParameters.Param[0] = myEncoderParameter; image.Save(outputMs, jpgEncoder, myEncoderParameters); data = outputMs.ToArray(); } #endregion } using (var stream = new FileStream(clippedBundleFile.FullName, FileMode.Append)) { stream.Write(data, 0, data.Length); } indexBuilder.SetValue(r, c, clippedTilePos, data.Length); clippedTilePos += data.Length; } } } if (clippedTilePos > 0) { indexBuilder.Save(clippedBundleFile.Directory.FullName + @"\" + new FileInfo(bundle.Index.Filename).Name); } } if (maxlevel >= 0 && level.Level >= maxlevel) { break; } } return(0); }
/// <summary> /// Saves the Bitmap as a JPG with options. /// </summary> /// <param name="bitmap">The bitmap.</param> /// <param name="path">The path.</param> /// <param name="quality">The quality.</param> public static void SaveJpg(this System.Drawing.Bitmap bitmap, string path, long quality) { System.Drawing.Imaging.ImageCodecInfo codecInfo = GetEncoderInfo("image/jpeg"); System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality; System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, quality); encoderParameters.Param[0] = encoderParameter; using(Stream st=File.Create(path)){ bitmap.Save(st,codecInfo,encoderParameters); } return; }
public static MemoryStream CreateImageForDB(Stream sFile, int intHeight, int intWidth) { var newStream = new MemoryStream(); var g = Image.FromStream(sFile); //Dim thisFormat = g.RawFormat if (intHeight > 0 & intWidth > 0) { int newHeight; int newWidth; newHeight = intHeight; newWidth = intWidth; Size imgSize; if (g.Width > newWidth | g.Height > newHeight) { imgSize = NewImageSize(g.Width, g.Height, newWidth, newHeight); imgHeight = imgSize.Height; imgWidth = imgSize.Width; } else { imgHeight = g.Height; imgWidth = g.Width; } } else { imgWidth = g.Width; imgHeight = g.Height; } var imgOutput1 = new Bitmap(g, imgWidth, imgHeight); Graphics bmpOutput = Graphics.FromImage(imgOutput1); bmpOutput.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; bmpOutput.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; var compressionRectange = new Rectangle(0, 0, imgWidth, imgHeight); bmpOutput.DrawImage(g, compressionRectange); System.Drawing.Imaging.ImageCodecInfo myImageCodecInfo; System.Drawing.Imaging.Encoder myEncoder; System.Drawing.Imaging.EncoderParameter myEncoderParameter; System.Drawing.Imaging.EncoderParameters myEncoderParameters; myImageCodecInfo = GetEncoderInfo("image/jpeg"); myEncoder = System.Drawing.Imaging.Encoder.Quality; myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 90); myEncoderParameters.Param[0] = myEncoderParameter; imgOutput1.Save(newStream, myImageCodecInfo, myEncoderParameters); g.Dispose(); imgOutput1.Dispose(); bmpOutput.Dispose(); return newStream; }
public EncoderParameter(Encoder encoder, int NumberOfValues, int Type, int Value) { WrappedEncoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, NumberOfValues, Type, Value); }
private void Convert_Click(object sender, EventArgs e) { if (!isDropped) { MessageBox.Show("Please drag files."); return; } else if (this.chkMergePDF.Checked && this.PDFTitle.Text.Equals("")) { MessageBox.Show("Please enter the PDF title."); return; } else if (!(this.chkMergePDF.Checked || this.chkCreateImages.Checked)) { MessageBox.Show("Please check"); return; } this.Status.Text = "Converting..."; int m_idx = 0; foreach (string fileImg in imgFiles) { int m_pos = imgFiles[m_idx].LastIndexOf('\\'); filepath = imgFiles[m_idx++].Substring(0, m_pos); //MessageBox.Show(m_idx + " " + filepath); savedPath = filepath + convertedDir + '\\'; System.IO.Directory.CreateDirectory(savedPath); string m_filename = ""; for (int ii = fileImg.LastIndexOf('\\') + 1; ii < fileImg.Length - 4; ii++) { m_filename += fileImg[ii]; } this.Status.Text = "Converting " + m_filename; Bitmap i = System.Drawing.Image.FromFile(fileImg) as Bitmap; var dpiX = i.HorizontalResolution; var dpiY = i.VerticalResolution; int iW = i.Width; int iH = i.Height; var temp = new Bitmap(iW / 2, iH, i.PixelFormat); temp.SetResolution(dpiX, dpiY); //MBDN code, 'GetEncoder' is a custom declared method //Trying to solve the problem; images drawn by 'Graphics' not being able to be opened on the photoshop app System.Drawing.Imaging.ImageCodecInfo jpgEncoder = this.GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); //180503-01 adjusted by adding (long)dpiX for the parameter, while dpiX is the original horizontal resolution of the referred image file. System.Drawing.Imaging.EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, (long)dpiX); myEncoderParameters.Param[0] = myEncoderParameter; /* * using (var gr = Graphics.FromImage(temp)) * { * gr.DrawImageUnscaled(i, 0, 0, iW, iH); * } * temp.Save(savedPath + m_filename + "_L.jpg", jpgEncoder, myEncoderParameters); */ string lPath = savedPath + m_filename + "_L.jpg"; string rPath = savedPath + m_filename + "_R.jpg"; convertedPaths.Add(lPath); convertedPaths.Add(rPath); int iW2 = iW / 2; for (int ii = 0; ii < iW2; ii++) { for (int jj = 0; jj < iH; jj++) { temp.SetPixel(ii, jj, i.GetPixel(ii, jj)); } } temp.Save(lPath); //temp.Save(lPath, jpgEncoder, myEncoderParameters); for (int ii = 0; ii < iW2; ii++) { for (int jj = 0; jj < iH; jj++) { temp.SetPixel(ii, jj, i.GetPixel(ii + iW2, jj)); } } temp.Save(rPath); //temp.Save(rPath, jpgEncoder, myEncoderParameters); /*180503-01, the color has lost its vividness, trying out different options. * using (var gr = Graphics.FromImage(temp)) * { * gr.Clear(Color.Transparent); * gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; * //gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; * gr.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; * * gr.DrawImage(i, new System.Drawing.Rectangle(0, 0, iW, iH)); * } * temp.Save(lPath, jpgEncoder, myEncoderParameters); * using (var gr = Graphics.FromImage(temp)) * { * gr.Clear(Color.Transparent); * gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; * gr.DrawImage(i, new System.Drawing.Rectangle(0, 0, iW, iH), new System.Drawing.Rectangle(iW / 2, 0, iW, iH), GraphicsUnit.Pixel); * } * temp.Save(rPath, jpgEncoder, myEncoderParameters); */ /*0502-01. succeeded in diving into two. failed to keep the original resolution * Bitmap i = Image.FromFile(fileImg) as Bitmap; * var dpiX = i.HorizontalResolution; * var dpiY = i.VerticalResolution; * MessageBox.Show(dpiX + " " + dpiY); * int iW = i.Width; * int iH = i.Height; * Rectangle cropRectL = new Rectangle(0, 0, iW / 2, iH); * Rectangle cropRectR = new Rectangle(iW / 2, 0, iW / 2, iH); * Bitmap target = new Bitmap(i); * * target.Clone(cropRectL, target.PixelFormat).Save(savedPath + m_filename + "_L.jpg"); * target.Clone(cropRectR, target.PixelFormat).Save(savedPath + m_filename + "_R.jpg"); */ /*0502-02. succeeded in diving into two, keeping the original resolution, but failed in having the files opened on photoshop * Bitmap i = Image.FromFile(fileImg) as Bitmap; * var dpiX = i.HorizontalResolution; * var dpiY = i.VerticalResolution; * * int iW = i.Width; * int iH = i.Height; * * var temp = new Bitmap(iW/2, iH, i.PixelFormat); * temp.SetResolution(dpiX, dpiY); * * using ( var gr = Graphics.FromImage(temp)) * { * gr.Clear(Color.Transparent); * gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; * gr.DrawImage(i, new Rectangle(0, 0, iW, iH)); * } * temp.Save(savedPath + m_filename + "_L.jpg"); * using (var gr = Graphics.FromImage(temp)) * { * gr.Clear(Color.Transparent); * gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; * gr.DrawImage(i, new Rectangle(0, 0, iW, iH), new Rectangle(iW/2, 0, iW, iH), GraphicsUnit.Pixel); * } * temp.Save(savedPath + m_filename + "_R.jpg"); */ /* 0501version * Bitmap i = Image.FromFile(fileImg) as Bitmap; * i.Save(savedPath + m_filename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg); * Rectangle cropRectL = new Rectangle(0, 0, i.Width/2, i.Height); * Rectangle cropRectR = new Rectangle(i.Width / 2, 0, i.Width / 2, i.Height); * * Bitmap newImageL = new Bitmap(cropRectL.Width, cropRectL.Height); * Bitmap newImageR = new Bitmap(cropRectR.Width, cropRectR.Height); * * Graphics gL = Graphics.FromImage(newImageL); * Graphics gR = Graphics.FromImage(newImageR); * * gL.DrawImage(i, cropRectL.X, cropRectL.Y); * string fileL = savedPath + m_filename + "_L.jpg"; * newImageL.Save(fileL, System.Drawing.Imaging.ImageFormat.Jpeg); * * gR.DrawImage(i, cropRectL, cropRectR, GraphicsUnit.Pixel); * string fileR = savedPath + m_filename + "_R.jpg"; * newImageR.Save(fileR, System.Drawing.Imaging.ImageFormat.Jpeg); * * imgFilesConverted.Add(fileL); * imgFilesConverted.Add(fileR); * * gL.Dispose(); * gR.Dispose(); * i.Dispose(); * newImageL.Dispose(); * newImageR.Dispose(); */ } string finishedMsg = "Image cut"; if (this.chkMergePDF.Checked) { toPDF(); finishedMsg = "Image cut & PDF merged"; } if (!this.chkCreateImages.Checked) { try { System.GC.Collect(); foreach (string img in convertedPaths) { File.Delete(img); } finishedMsg += " & Image Deleted"; } catch (IOException ee) { MessageBox.Show("Not able to delete images. error code : " + ee); } } MessageBox.Show(finishedMsg); this.setLog(); this.initDisplay(); this.Status.Text = "Drag and drop images"; }
/// <summary> /// Initializes a new instance of the <see cref="T:Common.Drawing.Imaging.EncoderParameter" /> class with the /// specified <see cref="T:Common.Drawing.Imaging.Encoder" /> object and two arrays of 64-bit integers. The two arrays /// represent an array integer ranges. Sets the <see cref="P:Common.Drawing.Imaging.EncoderParameter.ValueType" /> /// property to <see cref="F:Common.Drawing.Imaging.EncoderParameterValueType.ValueTypeLongRange" />, and sets the /// <see cref="P:Common.Drawing.Imaging.EncoderParameter.NumberOfValues" /> property to the number of elements in the /// <paramref name="rangebegin" /> array, which must be the same as the number of elements in the /// <paramref name="rangeend" /> array. /// </summary> /// <param name="encoder"> /// An <see cref="T:Common.Drawing.Imaging.Encoder" /> object that encapsulates the globally unique /// identifier of the parameter category. /// </param> /// <param name="rangebegin"> /// An array of 64-bit integers that specifies the minimum values for the integer ranges. The /// integers in the array must be nonnegative. The 64-bit integers are converted to 32-bit integers before they are /// stored in the <see cref="T:Common.Drawing.Imaging.EncoderParameter" /> object. /// </param> /// <param name="rangeend"> /// An array of 64-bit integers that specifies the maximum values for the integer ranges. The /// integers in the array must be nonnegative. The 64-bit integers are converted to 32-bit integers before they are /// stored in the <see cref="T:Common.Drawing.Imaging.EncoderParameters" /> object. A maximum value of a given index is /// paired with the minimum value of the same index. /// </param> public EncoderParameter(Encoder encoder, long[] rangebegin, long[] rangeend) { WrappedEncoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, rangebegin, rangeend); }
public static TrueBitmapInfo GetThumbnail(System.Drawing.Bitmap sourceBitmap, int destWidth, int destHeight) { System.Drawing.Image imgSource = sourceBitmap; int sW, sH; // 按比例缩放 int sWidth = imgSource.Width; int sHeight = imgSource.Height; if (sHeight > destHeight || sWidth > destWidth) { if ((sWidth*destHeight) > (sHeight*destWidth)) { sW = destWidth; sH = (destWidth*sHeight)/sWidth; } else { sH = destHeight; sW = (sWidth*destHeight)/sHeight; } } else { sW = sWidth; sH = sHeight; } var info = new TrueBitmapInfo(); var outBmp = new System.Drawing.Bitmap(destWidth, destHeight); var outSmallBmp = new System.Drawing.Bitmap(sW, sH); info.Bitmap = outBmp; System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(outBmp); g.Clear(System.Drawing.Color.Transparent); // 设置画布的描绘质量 g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; var rect = new System.Drawing.Rectangle((destWidth - sW) / 2, (destHeight - sH) / 2, sW, sH); g.DrawImage(imgSource, rect, 0, 0, imgSource.Width, imgSource.Height, System.Drawing.GraphicsUnit.Pixel); g.Dispose(); g = System.Drawing.Graphics.FromImage(outSmallBmp); g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; var rect1 = new System.Drawing.Rectangle(0, 0, sW, sH); g.DrawImage(imgSource, rect1, 0, 0, imgSource.Width, imgSource.Height, System.Drawing.GraphicsUnit.Pixel); g.Dispose(); info.SmallBitmap = outSmallBmp; info.ImageRect = rect; // 以下代码为保存图片时,设置压缩质量 var encoderParams = new System.Drawing.Imaging.EncoderParameters(); var quality = new long[1]; quality[0] = 100; var encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; try { //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象。 System.Drawing.Imaging.ImageCodecInfo[] arrayIci = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); foreach (System.Drawing.Imaging.ImageCodecInfo t in arrayIci) { if (t.FormatDescription.Equals("JPEG")) { break; } } return info; } catch { return new TrueBitmapInfo(); } }
/// <summary> /// Initializes a new instance of the <see cref="T:Common.Drawing.Imaging.EncoderParameter" /> class with the /// specified <see cref="T:Common.Drawing.Imaging.Encoder" /> object and a pair of 32-bit integers. The pair of /// integers represents a fraction, the first integer being the numerator, and the second integer being the /// denominator. Sets the <see cref="P:Common.Drawing.Imaging.EncoderParameter.ValueType" /> property to /// <see cref="F:Common.Drawing.Imaging.EncoderParameterValueType.ValueTypeRational" />, and sets the /// <see cref="P:Common.Drawing.Imaging.EncoderParameter.NumberOfValues" /> property to 1. /// </summary> /// <param name="encoder"> /// An <see cref="T:Common.Drawing.Imaging.Encoder" /> object that encapsulates the globally unique /// identifier of the parameter category. /// </param> /// <param name="numerator">A 32-bit integer that represents the numerator of a fraction. Must be nonnegative. </param> /// <param name="demoninator">A 32-bit integer that represents the denominator of a fraction. Must be nonnegative. </param> public EncoderParameter(Encoder encoder, int numerator, int denominator) { WrappedEncoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, numerator, denominator); }
private void Save(Stream stream, Bitmap img, long quality) { System.Drawing.Imaging.EncoderParameter qualityParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); System.Drawing.Imaging.ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg"); if (jpegCodec == null) return; System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1); encoderParams.Param[0] = qualityParam; img.Save(stream, jpegCodec, encoderParams); }
public static void SaveImage(System.Drawing.Image Image, string Destination) { System.Drawing.Imaging.ImageCodecInfo jgpEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); 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, (long)Settings.ImageQuality); myEncoderParameters.Param[0] = myEncoderParameter; Image.Save(Destination, jgpEncoder, myEncoderParameters); }
/// <summary> /// 指定ファイルにEXIFデータを書き込む /// 保持しているデータ以外はすべてクリアする /// </summary> /// <param name="filePath">元ファイルパス</param> /// <param name="dstPath">書き換え後ファイルの保存先 / 指定なしの場合はsrcに上書きする</param> /// <returns>0 or エラー値</returns> public int SetExifToImage(string filePath, string dstPath = null) { if (string.IsNullOrEmpty(filePath)) { return((int)ErrorNumber.ArgumentsNull); } if (!System.IO.File.Exists(filePath)) { return((int)ErrorNumber.FileNotFound); } if (string.IsNullOrEmpty(dstPath)) { dstPath = filePath; } else { try { if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(dstPath)))) { return((int)ErrorNumber.DirectoryNotFound); } } catch { return((int)ErrorNumber.FileIOException); } } System.Drawing.Bitmap bmp = null; try { bmp = new System.Drawing.Bitmap(filePath); System.Drawing.Imaging.PropertyItem pp; if (bmp.PropertyItems.Count() < 0) { pp = bmp.PropertyItems[0]; } else { // PropertyItem作成 System.Drawing.Bitmap tb = new System.Drawing.Bitmap(1, 1); System.IO.MemoryStream mst = new System.IO.MemoryStream(); tb.Save(mst, System.Drawing.Imaging.ImageFormat.Jpeg); tb = new System.Drawing.Bitmap(mst); pp = tb.PropertyItems[0]; } foreach (System.Drawing.Imaging.PropertyItem pi in bmp.PropertyItems) { bmp.RemovePropertyItem(pi.Id); } foreach (EXIF_TAGS et in TagList) { pp.Id = et.tag; pp.Type = (short)et.type; pp.Value = new byte[et.data.Length]; et.data.CopyTo(pp.Value, 0); if (et.type == (int)ExifType.ASCII) { if ((et.data[et.data.Length - 1] != '\0') && AutoAdjust) { byte[] tmpb = new byte[et.data.Length]; et.data.CopyTo(tmpb, 0); pp.Value = new byte[et.data.Length + 1]; tmpb.CopyTo(pp.Value, 0); pp.Value[et.data.Length] = (byte)'\0'; } } switch ((ExifType)Enum.ToObject(typeof(ExifType), et.type)) { case ExifType.BYTE: pp.Len = 1; break; case ExifType.SHORT: pp.Len = 2; break; case ExifType.LONG: case ExifType.SLONG: pp.Len = 4; break; case ExifType.RATIONAL: case ExifType.SRATIONAL: pp.Len = 8; break; case ExifType.UNDEFINED: case ExifType.ASCII: pp.Len = pp.Value.Length; break; default: pp.Len = 0; break; } bmp.SetPropertyItem(pp); } System.Drawing.Imaging.EncoderParameters eps = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.EncoderParameter ep = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, JpegQuality); eps.Param[0] = ep; System.Drawing.Imaging.ImageCodecInfo jici = null; foreach (System.Drawing.Imaging.ImageCodecInfo ici in System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()) { if (ici.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid) { jici = ici; break; } } if (jici is null) { return((int)ErrorNumber.ParameterNull); } if (!filePath.Equals(dstPath)) { bmp.Save(dstPath, jici, eps); bmp.Dispose(); } else { string tempPath = DateTime.Now.ToString("yyyyMMddHHmmssfff"); bmp.Save(tempPath, jici, eps); bmp.Dispose(); try { System.IO.File.Delete(filePath); System.IO.File.Move(tempPath, dstPath); } finally { if (System.IO.File.Exists(tempPath)) { System.IO.File.Delete(tempPath); } } } } catch { return((int)ErrorNumber.Unknown); } finally { if (bmp != null) { bmp.Dispose(); } } return((int)ErrorNumber.NoError); }
public EncoderParameter(Encoder encoder, int numberValues, EncoderParameterValueType type, IntPtr value) { WrappedEncoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, NumberOfValues, (System.Drawing.Imaging.EncoderParameterValueType)type, value); }
/// <summary> /// 加图片水印 /// </summary> /// <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 Path, string filename, string watermarkFilename, int watermarkStatus, int quality, int watermarkTransparency) { System.Drawing.Image img = System.Drawing.Image.FromFile(Path); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(img); //设置高质量插值法 //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; System.Drawing.Image watermark = new System.Drawing.Bitmap(watermarkFilename); if (watermark.Height >= img.Height || watermark.Width >= img.Width) { return; } System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes(); System.Drawing.Imaging.ColorMap colorMap = new System.Drawing.Imaging.ColorMap(); colorMap.OldColor = System.Drawing.Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = System.Drawing.Color.FromArgb(0, 0, 0, 0); System.Drawing.Imaging.ColorMap[] remapTable = { colorMap }; imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.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} }; System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.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 System.Drawing.Rectangle(xpos, ypos, watermark.Width, watermark.Height), 0, 0, watermark.Width, watermark.Height, System.Drawing.GraphicsUnit.Pixel, imageAttributes); System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.ImageCodecInfo ici = null; foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs) { //if (codec.MimeType.IndexOf("jpeg") > -1) if (codec.MimeType.Contains("jpeg")) { ici = codec; } } System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) { quality = 80; } qualityParam[0] = quality; System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.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(); }
private void run() { string dir = this.textBox2.Text; string outputDir = Path.Combine(dir, "output"); string bookName = this.textBox7.Text; string runDir = AppDomain.CurrentDomain.BaseDirectory; string chapterHtml = File.ReadAllText(Path.Combine(runDir, "chapter.html")); string ePubRawFolder = Path.Combine(runDir, "ePub"); FileHelper.DeleteDirectory(outputDir); FileHelper.CreateDirectory(outputDir); #region JPEG Params var 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; System.Drawing.Imaging.ImageCodecInfo jpegICI = null; System.Drawing.Imaging.ImageCodecInfo[] arrayICI = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICI = arrayICI[x]; break; } } #endregion #region Process Images int topCut = 0; int.TryParse(this.textBox3.Text, out topCut); int bottomCut = 0; int.TryParse(this.textBox4.Text, out bottomCut); int xuKuan = 0; int.TryParse(this.textBox5.Text, out xuKuan); int imageWidth = 1080; int imageHeight = 1440; string[] files = Directory.GetFiles(dir); int dirIdx = 1; int fenJuanPageCount = 0; int.TryParse(this.textBox6.Text, out fenJuanPageCount); List<string> folders = new List<string>(); string imgDesDir = outputDir; int fileIdx = 0; if (fenJuanPageCount > 0) { imgDesDir = Path.Combine(outputDir, dirIdx.ToString().PadLeft(3, '0')); } FileHelper.CreateDirectory(imgDesDir); folders.Add(imgDesDir); foreach (string imgFile in files) { fileIdx++; if (fenJuanPageCount > 0 && fileIdx > fenJuanPageCount) { dirIdx++; imgDesDir = Path.Combine(outputDir, dirIdx.ToString().PadLeft(3, '0')); FileHelper.CreateDirectory(imgDesDir); folders.Add(imgDesDir); fileIdx = 1; } string fileName = Path.GetFileNameWithoutExtension(imgFile); this.showLog("Processing " + imgFile + ", Total " + files.Length); //Temp Pic var objPic = new Bitmap(imgFile); int tempPicHeight = imageHeight + topCut + bottomCut; int tempPicWidth = (int)(objPic.Width * ((float)tempPicHeight / objPic.Height)); var objTempPic = new Bitmap(tempPicWidth, tempPicHeight); using (Graphics g = Graphics.FromImage(objTempPic)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(objPic, 0, 0, objTempPic.Width, objTempPic.Height); } objPic.Dispose(); //New Pic int startX = 0; int idx = 1; while (startX < tempPicWidth) { var objNewPic = new Bitmap(imageWidth, imageHeight); using (Graphics g = Graphics.FromImage(objNewPic)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle(Brushes.White, 0, 0, imageWidth, imageHeight); g.DrawImage(objTempPic, 0, 0, new Rectangle(startX, topCut, imageWidth, imageHeight), GraphicsUnit.Pixel); } objNewPic.Save(Path.Combine(imgDesDir, fileName + idx.ToString() + ".jpg"), jpegICI, encoderParams); objNewPic.Dispose(); startX += imageWidth - xuKuan; idx++; } objTempPic.Dispose(); } #endregion #region Create ePub if (this.checkBox1.Checked) { for (int i = 0; i < folders.Count; i++) { this.showLog("Creating ePub for folder " + i); string ePubFolder = Path.Combine(outputDir, "epub" + i); FileHelper.CreateDirectory(ePubFolder); FileHelper.CopyDirectoryTo(ePubRawFolder, ePubFolder, ePubRawFolder); string strItems = string.Empty; string strItemRef = string.Empty; string strNavPoints = string.Empty; string[] images = Directory.GetFiles(folders[i]); for (int j = 0; j < images.Length; j++) { string imageFile = images[j]; string imageFileName = Path.GetFileName(imageFile); string page = (j + 1).ToString(); FileHelper.MoveFile(imageFile, Path.Combine(ePubFolder, "OPS", "images", imageFileName)); string pageHtml = chapterHtml.Replace("[%page%]", page).Replace("[%image%]", imageFileName); File.WriteAllText(Path.Combine(ePubFolder, "OPS", "chapter" + page + ".html"), pageHtml); strItems += "<item id=\"chapter" + page + "\" href=\"chapter" + page + ".html\" media-type=\"application/xhtml+xml\"/>" + Environment.NewLine; strItemRef += "<itemref idref=\"chapter" + page + "\" linear=\"yes\"/>" + Environment.NewLine; strNavPoints += "<navPoint id=\"chapter" + page + "\" playOrder=\"" + page + "\">" + Environment.NewLine + "<navLabel><text>第" + page + "页</text></navLabel>" + Environment.NewLine + "<content src=\"chapter" + page + ".html\"/>" + Environment.NewLine + "</navPoint>" + Environment.NewLine; } string fbNcxPath = Path.Combine(ePubFolder, "OPS", "fb.ncx"); string fbOpfPath = Path.Combine(ePubFolder, "OPS", "fb.opf"); File.WriteAllText(fbNcxPath, File.ReadAllText(fbNcxPath).Replace("[%navPoints%]", strNavPoints)); File.WriteAllText(fbOpfPath, File.ReadAllText(fbOpfPath).Replace("[%items%]", strItems).Replace("[%itemrefs%]", strItemRef)); string ePubFileName = bookName + i.ToString() + ".epub"; Process p = new Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.FileName = Path.Combine(runDir, "zip.exe"); p.StartInfo.Arguments = "-r " + ePubFileName + " META-INF OPS mimetype"; p.StartInfo.WorkingDirectory = ePubFolder; p.Start(); p.WaitForExit(); FileHelper.MoveFile(Path.Combine(ePubFolder, ePubFileName), Path.Combine(outputDir, ePubFileName)); //FileHelper.CreateZipForDir(ePubFolder, Path.Combine(outputDir, bookName + i.ToString() + ".epub")); } } #endregion this.showLog("Done"); this.Invoke(new Action(resetButton)); }
/// <summary> /// 在图片上生成图片水印 /// </summary> /// <param name="sourcePath">原图片路径</param> /// <param name="targetPath">另存为路径</param> /// <param name="waterMarkFilePath">水印图片路径</param> /// <param name="positionType">图片水印位置:UL,UM , UR , ML , MM , MR , BL , BM , BR ,CUSTORM 为自定义.</param> /// <param name="quality">是否是高质量图片 取值范围0--100</param> /// <param name="watermarkTransparency">图片水印透明度 取值范围1--10 (10为不透明)</param> /// <returns></returns> public static bool PictureWatermark(string sourcePath, string targetPath, string waterMarkFilePath, PicWaterMarkPosition positionType, int quality, int watermarkTransparency) { System.Drawing.Image img = System.Drawing.Image.FromFile(sourcePath); System.Drawing.Bitmap outPut = new System.Drawing.Bitmap(img); try { #region using using (Graphics g = Graphics.FromImage(outPut)) { //设置高质量插值法 //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; System.Drawing.Image markImg = new System.Drawing.Bitmap(waterMarkFilePath); if (markImg.Height >= img.Height || markImg.Width >= img.Width) { return false; } System.Drawing.Imaging.ImageAttributes imageAttributes = new System.Drawing.Imaging.ImageAttributes(); System.Drawing.Imaging.ColorMap colorMap = new System.Drawing.Imaging.ColorMap(); colorMap.OldColor = System.Drawing.Color.FromArgb(255, 0, 255, 0); colorMap.NewColor = System.Drawing.Color.FromArgb(0, 0, 0, 0); System.Drawing.Imaging.ColorMap[] remapTable = { colorMap }; imageAttributes.SetRemapTable(remapTable, System.Drawing.Imaging.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} }; System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix(colorMatrixElements); imageAttributes.SetColorMatrix(colorMatrix, System.Drawing.Imaging.ColorMatrixFlag.Default, System.Drawing.Imaging.ColorAdjustType.Bitmap); int xpos = 0; int ypos = 0; #region position switch (positionType) { case PicWaterMarkPosition.UL: xpos = (int)(img.Width * (float).01); ypos = (int)(img.Height * (float).01); break; case PicWaterMarkPosition.UM: xpos = (int)((img.Width * (float).50) - (markImg.Width / 2)); ypos = (int)(img.Height * (float).01); break; case PicWaterMarkPosition.UR: xpos = (int)((img.Width * (float).99) - (markImg.Width)); ypos = (int)(img.Height * (float).01); break; case PicWaterMarkPosition.ML: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).50) - (markImg.Height / 2)); break; case PicWaterMarkPosition.MM: xpos = (int)((img.Width * (float).50) - (markImg.Width / 2)); ypos = (int)((img.Height * (float).50) - (markImg.Height / 2)); break; case PicWaterMarkPosition.MR: xpos = (int)((img.Width * (float).99) - (markImg.Width)); ypos = (int)((img.Height * (float).50) - (markImg.Height / 2)); break; case PicWaterMarkPosition.BL: xpos = (int)(img.Width * (float).01); ypos = (int)((img.Height * (float).99) - markImg.Height); break; case PicWaterMarkPosition.BM: xpos = (int)((img.Width * (float).50) - (markImg.Width / 2)); ypos = (int)((img.Height * (float).99) - markImg.Height); break; case PicWaterMarkPosition.BR: xpos = (int)((img.Width * (float).99) - (markImg.Width)); ypos = (int)((img.Height * (float).99) - markImg.Height); break; } #endregion position g.DrawImage(markImg, new System.Drawing.Rectangle(xpos, ypos, markImg.Width, markImg.Height), 0, 0, markImg.Width, markImg.Height, System.Drawing.GraphicsUnit.Pixel, imageAttributes); System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.ImageCodecInfo ici = null; foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs) { if (codec.MimeType.IndexOf("jpeg") > -1) { ici = codec; } } System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(); long[] qualityParam = new long[1]; if (quality < 0 || quality > 100) { quality = 80; } qualityParam[0] = quality; System.Drawing.Imaging.EncoderParameter encoderParam = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qualityParam); encoderParams.Param[0] = encoderParam; if (ici != null) { outPut.Save(targetPath, ici, encoderParams); } else { outPut.Save(targetPath); } g.Dispose(); markImg.Dispose(); imageAttributes.Dispose(); } #endregion using } catch (Exception) { return false; } finally { if (outPut != null) { outPut.Dispose(); } if (img != null) { img.Dispose(); } } return true; }
public static void CreateImage(string sFile, int intHeight, int intWidth) { string tmp; if (sFile.ToUpper().Contains(".JPG")) { tmp = sFile.ToUpper().Replace(".JPG", "_TEMP.JPG"); } else if (sFile.ToUpper().Contains(".PNG")) { tmp = sFile.ToUpper().Replace(".PNG", "_TEMP.PNG"); } else if (sFile.ToUpper().Contains(".GIF")) { tmp = sFile.ToUpper().Replace(".GIF", "_TEMP.GIF"); } else if (sFile.ToUpper().Contains(".JPEG")) { tmp = sFile.ToUpper().Replace(".JPEG", "_TEMP.JPEG"); } else { tmp = sFile; } File.Copy(sFile, tmp); var g = Image.FromFile(tmp); //Dim thisFormat = g.RawFormat int newHeight; int newWidth; newHeight = intHeight; newWidth = intWidth; Size imgSize; if (g.Width > newWidth | g.Height > newHeight) { imgSize = NewImageSize(g.Width, g.Height, newWidth, newHeight); imgHeight = imgSize.Height; imgWidth = imgSize.Width; } else { imgHeight = g.Height; imgWidth = g.Width; } var imgOutput1 = new Bitmap(g, imgWidth, imgHeight); Graphics bmpOutput = Graphics.FromImage(imgOutput1); bmpOutput.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; bmpOutput.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; var compressionRectange = new Rectangle(0, 0, imgWidth, imgHeight); bmpOutput.DrawImage(g, compressionRectange); System.Drawing.Imaging.ImageCodecInfo myImageCodecInfo; System.Drawing.Imaging.Encoder myEncoder; System.Drawing.Imaging.EncoderParameter myEncoderParameter; System.Drawing.Imaging.EncoderParameters myEncoderParameters; myImageCodecInfo = GetEncoderInfo("image/jpeg"); myEncoder = System.Drawing.Imaging.Encoder.Quality; myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 90); myEncoderParameters.Param[0] = myEncoderParameter; imgOutput1.Save(sFile, myImageCodecInfo, myEncoderParameters); g.Dispose(); imgOutput1.Dispose(); File.Delete(tmp); }
private EncoderParameter(System.Drawing.Imaging.EncoderParameter encoderParameter) { WrappedEncoderParameter = encoderParameter; }
private void ButtonMove_Click(object sender, RoutedEventArgs e) { if (this.ComboBoxServerFolder.SelectedItem != null) { ServerFolder serverFolder = (ServerFolder)this.ComboBoxServerFolder.SelectedItem; if (this.ListViewScannedFiles.SelectedItems.Count != 0) { ScannedFile scannedFile = (ScannedFile)this.ListViewScannedFiles.SelectedItem; YellowstonePathology.Business.Document.CaseDocumentCollection caseDocumentCollection = new Business.Document.CaseDocumentCollection(this.m_ReportNo); YellowstonePathology.Business.Document.CaseDocumentCollection requisitions = caseDocumentCollection.GetRequisitions(); int nextReqNo = requisitions.Count + 1; YellowstonePathology.Business.OrderIdParser orderIdParser = new Business.OrderIdParser(this.m_ReportNo); if (orderIdParser.ReportNo != null || orderIdParser.MasterAccessionNo != null) { string newFileName = System.IO.Path.Combine(YellowstonePathology.Document.CaseDocumentPath.GetPath(orderIdParser), this.m_ReportNo + ".REQ." + nextReqNo.ToString() + ".TIF"); if (orderIdParser.IsLegacyReportNo == false) { string masterAccessionNo = orderIdParser.MasterAccessionNo; newFileName = System.IO.Path.Combine(YellowstonePathology.Document.CaseDocumentPath.GetPath(orderIdParser), masterAccessionNo + ".REQ." + nextReqNo.ToString() + ".TIF"); } if (scannedFile.Extension.ToUpper() == ".TIF") { System.IO.File.Copy(scannedFile.Name, newFileName); } else if (scannedFile.Extension.ToUpper() == ".JPG") { System.Drawing.Imaging.ImageCodecInfo myImageCodecInfo; System.Drawing.Imaging.Encoder myEncoder; System.Drawing.Imaging.EncoderParameter myEncoderParameter; System.Drawing.Imaging.EncoderParameters myEncoderParameters; myImageCodecInfo = GetEncoderInfo("image/tiff"); myEncoder = System.Drawing.Imaging.Encoder.Compression; myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, (long)System.Drawing.Imaging.EncoderValue.CompressionCCITT4); myEncoderParameters.Param[0] = myEncoderParameter; System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(scannedFile.Name); bitmap.Save(newFileName, myImageCodecInfo, myEncoderParameters); bitmap.Dispose(); } System.IO.File.Delete(scannedFile.Name); this.StackPanelImage.Children.RemoveRange(0, this.StackPanelImage.Children.Count); this.m_ServerFileCollection = new ScannedFileCollection(); this.m_ServerFileCollection.LoadFiles(serverFolder.Path); this.NotifyPropertyChanged("ServerFileCollection"); this.ListViewScannedFiles.SelectedIndex = 0; if (orderIdParser.IsLegacyReportNo) this.ReportNo = this.ReportNo.Substring(0, 4); else this.ReportNo = this.ReportNo.Substring(0, 3); } else { MessageBox.Show("The Master Accession No should be used for the new style report - 13-123.S \nThe Report No needs to be used for old style reports - S13-123", "Use correct identifier"); } } } }
/// <summary> /// Initializes a new instance of the <see cref="T:Common.Drawing.Imaging.EncoderParameter" /> class with the /// specified <see cref="T:Common.Drawing.Imaging.Encoder" /> object and one 8-bit value. Sets the /// <see cref="P:Common.Drawing.Imaging.EncoderParameter.ValueType" /> property to /// <see cref="F:Common.Drawing.Imaging.EncoderParameterValueType.ValueTypeUndefined" /> or /// <see cref="F:Common.Drawing.Imaging.EncoderParameterValueType.ValueTypeByte" />, and sets the /// <see cref="P:Common.Drawing.Imaging.EncoderParameter.NumberOfValues" /> property to 1. /// </summary> /// <param name="encoder"> /// An <see cref="T:Common.Drawing.Imaging.Encoder" /> object that encapsulates the globally unique /// identifier of the parameter category. /// </param> /// <param name="value"> /// A byte that specifies the value stored in the /// <see cref="T:Common.Drawing.Imaging.EncoderParameter" /> object. /// </param> /// <param name="undefined"> /// If true, the <see cref="P:Common.Drawing.Imaging.EncoderParameter.ValueType" /> property is set /// to <see cref="F:Common.Drawing.Imaging.EncoderParameterValueType.ValueTypeUndefined" />; otherwise, the /// <see cref="P:Common.Drawing.Imaging.EncoderParameter.ValueType" /> property is set to /// <see cref="F:Common.Drawing.Imaging.EncoderParameterValueType.ValueTypeByte" />. /// </param> public EncoderParameter(Encoder encoder, byte value, bool undefined) { WrappedEncoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, value, undefined); }
/// <summary> /// Initializes a new instance of the <see cref="T:Common.Drawing.Imaging.EncoderParameter" /> class with the /// specified <see cref="T:Common.Drawing.Imaging.Encoder" /> object and one 64-bit integer. Sets the /// <see cref="P:Common.Drawing.Imaging.EncoderParameter.ValueType" /> property to /// <see cref="F:Common.Drawing.Imaging.EncoderParameterValueType.ValueTypeLong" /> (32 bits), and sets the /// <see cref="P:Common.Drawing.Imaging.EncoderParameter.NumberOfValues" /> property to 1. /// </summary> /// <param name="encoder"> /// An <see cref="T:Common.Drawing.Imaging.Encoder" /> object that encapsulates the globally unique /// identifier of the parameter category. /// </param> /// <param name="value"> /// A 64-bit integer that specifies the value stored in the /// <see cref="T:Common.Drawing.Imaging.EncoderParameter" /> object. Must be nonnegative. This parameter is converted /// to a 32-bit integer before it is stored in the <see cref="T:Common.Drawing.Imaging.EncoderParameter" /> object. /// </param> public EncoderParameter(Encoder encoder, long value) { WrappedEncoderParameter = new System.Drawing.Imaging.EncoderParameter(encoder, value); }
/// <summary> /// Save a card as JPEG file /// </summary> /// <param name="fileName">path to the file to save</param> /// <param name="resolution">image resolution</param> /// <param name="quality">image quality</param> /// <param name="showQsos">Boolean to indicate whether the card should include QSO info</param> private void SaveCardAsJpeg(string fileName, int resolution, int quality, bool showQsos) { // create visual of the card CardTabItem cti = mainTabControl.SelectedItem as CardTabItem; if(cti != null) { CardWF card = cti.cardPanel.QslCard.Clone(); card.IsInDesignMode = false; FormsCardView cView = new FormsCardView(card); List<List<DispQso>> dispQsos = new List<List<DispQso>>(); if(card.QsosBox != null) { if(qsosView.DisplayQsos.Count > 0 && showQsos) { dispQsos = qsosView.DisplayQsos.GetDispQsosList(card); } } float scale = (float)resolution / 100.0F; int bitmapWidth = (int)((float)card.Width * scale); int bitmapHeight = (int)((float)card.Height * scale); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(bitmapWidth, bitmapHeight); bitmap.SetResolution(resolution, resolution); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap); graphics.ScaleTransform(scale, scale); cView.PaintCard(graphics, dispQsos.Count > 0 ? dispQsos[0] : null, 96F / resolution); graphics.Dispose(); System.Drawing.Imaging.ImageCodecInfo jpgEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); System.Drawing.Imaging.Encoder qualityEncoder = System.Drawing.Imaging.Encoder.Quality; System.Drawing.Imaging.EncoderParameter encoderParameter = new System.Drawing.Imaging.EncoderParameter(qualityEncoder, quality); System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1); encoderParams.Param[0] = encoderParameter; bitmap.Save(fileName, jpgEncoder, encoderParams); bitmap.Dispose(); } }
private System.Drawing.Image FormatImage(HtmlInputFile file, string savePath,string Imgsize) { //width,height,size int fix = Convert.ToInt32(Imgsize); int nHeight = 0; int nWidth = 0; int maxSize = 3000; //if (!(type == "jpg" || type == "bmp" || type == "gif" || type == "jpeg" || type == "png")) { throw new Exception("type error"); } //validate formatter int size = (int)((float)file.PostedFile.ContentLength / (float)1024); //byte exchange kb if (size > maxSize) { throw new Exception("img size:" + size.ToString() + "KB,Maximum image size is 200KB! "); } if (System.IO.File.Exists(savePath)) { System.IO.File.Delete(savePath); } using (System.Drawing.Image Cimage = System.Drawing.Image.FromStream(file.PostedFile.InputStream)) { if (Cimage.Width > nWidth || Cimage.Height > nHeight) { if (Cimage.Width >= Cimage.Height) { nWidth = fix; nHeight = Convert.ToInt32((Convert.ToDouble(nWidth) / Convert.ToDouble(Cimage.Width)) * Convert.ToDouble(Cimage.Height)); } else { nHeight = fix; nWidth = Convert.ToInt32((Convert.ToDouble(nHeight) / Convert.ToDouble(Cimage.Height)) * Convert.ToDouble(Cimage.Width)); } Bitmap newimage = new Bitmap(Cimage, nWidth, nHeight); System.Drawing.Imaging.ImageCodecInfo jpegEncoder = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().Where(ks => ks.MimeType == "image/jpeg").FirstOrDefault(); 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, 100L); myEncoderParameters.Param[0] = myEncoderParameter; newimage.Save(Server.MapPath(savePath), jpegEncoder, myEncoderParameters); return Cimage; } else { Cimage.Save(Server.MapPath(savePath)); return Cimage; } } Response.Write("add sucessful."); }