/// <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 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(); }
public static byte[] ReduceWeightImage(System.Drawing.Image image, long minByteWeight, long maxByteWeight) { byte[] source = GetBytes(image); if (source.Length < maxByteWeight) { return(source); } if (minByteWeight > 0 && maxByteWeight > 0) { if (minByteWeight > maxByteWeight) { (minByteWeight, maxByteWeight) = (maxByteWeight, minByteWeight); } if (maxByteWeight - minByteWeight < 50) { maxByteWeight = minByteWeight + 50; } System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders(); string mimeType = GetMimeType(image); System.Drawing.Imaging.ImageCodecInfo imageCodecInfo = codecs[1]; System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality; System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); return(ReduceWeightImageProcess(source, source, minByteWeight, maxByteWeight, imageCodecInfo, encoder, encoderParameters, source.LongLength * 85L / 1166927L)); } return(source); }
public static void writeToFile(COMMON.ByteMatrix matrix, System.Drawing.Imaging.ImageFormat format, string file) { System.Drawing.Imaging.EncoderParameters eps = new System.Drawing.Imaging.EncoderParameters(); eps.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality,100L); Bitmap bmap = toBitmap(matrix); bmap.Save(file,format); }
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); }
public void SaveImage(string fileName, long size, int no) { //画像ファイルを読み込む System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(fileName); //イメージエンコーダに関する情報を取得する System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg"); try { //EncoderParameterオブジェクトを1つ格納できる //EncoderParametersクラスの新しいインスタンスを初期化 //ここでは品質のみ指定するため1つだけ用意する System.Drawing.Imaging.EncoderParameters eps = getOptiumQuarity(size, bmp, ici); //ファイル名を取得 string saveName = getSaveFileName(fileName, size, no); //保存する bmp.Save(saveName, ici, eps); bmp.Dispose(); eps.Dispose(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public byte[] compressPNG(byte[] srcBytes) { //byte[] result; MemoryStream ms = new MemoryStream(srcBytes); /*MemoryStream output = new MemoryStream(); * using (MagickImage image = new MagickImage(ms)) * { * image.Format = MagickFormat.Jpeg; * image.Quality = 80; * image.Depth = 8; * image.Write(output); * } * result = output.GetBuffer(); * return result;*/ ms.Position = 0; Image srcBitmap = Bitmap.FromStream(ms); MemoryStream output = new MemoryStream(); System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(2); ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 8L); ep.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 80L); srcBitmap.Save(output, GetEncoderInfo(), ep); return(output.GetBuffer()); }
static void Main(string[] args) { foreach (string file in args) { try { System.Console.Write("Reading file: {0} ... ", file); using (System.Drawing.Image image = System.Drawing.Image.FromFile(file)) { System.Console.WriteLine("Done"); System.IO.FileInfo info = new System.IO.FileInfo(file); string output = file.Replace(info.Extension, ".jpg"); System.Console.Write("Writing file: {0} ... ", output); // Create parameters to specify quality. System.Drawing.Imaging.ImageCodecInfo codec = Program.getCodecInfo("image/jpeg"); System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality; System.Drawing.Imaging.EncoderParameters parameters = new System.Drawing.Imaging.EncoderParameters(1); parameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(encoder, 100L); // Write the file. image.Save(output, codec, parameters); System.Console.WriteLine("Done"); } } catch (System.Exception e) { System.Console.WriteLine("Error processing file '", file, ", ", e.Message); } } }
public static byte[] ResizeImageToByte(string fileName, int width, int height) { using (Bitmap bmp = (Bitmap) new Bitmap(fileName).Clone()) { Size newSize = new Size(width, height); using (Bitmap newBmp = new Bitmap((System.Drawing.Image)bmp, newSize)) { using (Graphics g = Graphics.FromImage(newBmp)) // 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, 75L); //Now draw the image on the instance of thumbnail Bitmap object g.DrawImage(bmp, new Rectangle(0, 0, newBmp.Width, newBmp.Height)); //newBmp.Save(newFileName, codec, eParams); //newBmp.Save(newFileName, Image.FromFile(fileName).RawFormat); MemoryStream ms = new MemoryStream(); newBmp.Save(ms, bmp.RawFormat); return(ms.GetBuffer()); } } } }
private void saveAllDimensionsToFolderToolStripMenuItem_Click(object sender, EventArgs e) { try { FolderBrowserDialog dlg = new FolderBrowserDialog(); dlg.Description = "Save images of all dimension to directory..."; dlg.ShowNewFolderButton = true; //dlg.RootFolder = System.Environment.SpecialFolder.; if (dlg.ShowDialog(this) == DialogResult.OK) { System.Drawing.Imaging.EncoderParameters parameters1 = new System.Drawing.Imaging.EncoderParameters(3); parameters1.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 2L); parameters1.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L); parameters1.Param[2] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 24L); foreach (Microsoft.AnalysisServices.Dimension d in dimension.Parent.Dimensions) { Bitmap img = VisualizeAttributeLattice.Render(d, VisualizeAttributeLattice.LatticeLayoutMethod.DeepestPathsFirst, showOnlyMultilevelRelationshipsToolStripMenuItem.Checked); img.Save(dlg.SelectedPath + "\\" + d.Name + ".jpg", VisualizeAttributeLattice.GetJpegCodec(), parameters1); img.Dispose(); } } } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } }
// --------------------------------------------------------------------------- /* * you DO NOT want to use classes within the System.Drawing namespace to * manipulate image files in ASP.NET applications, see the warning here: * http://msdn.microsoft.com/en-us/library/system.drawing.aspx */ public byte[] CreatePdf(long quality) { using (MemoryStream msDoc = new MemoryStream()) { Image img = null; using (System.Drawing.Bitmap dotnetImg = new System.Drawing.Bitmap(RESOURCE)) { // set codec to jpeg type => jpeg index codec is "1" System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1]; // set parameters for image quality System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1); eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.Quality, quality ); using (MemoryStream msImg = new MemoryStream()) { dotnetImg.Save(msImg, codec, eParams); msImg.Position = 0; img = Image.GetInstance(msImg); img.SetAbsolutePosition(15, 15); // step 1 using (Document document = new Document()) { // step 2 PdfWriter.GetInstance(document, msDoc); // step 3 document.Open(); // step 4 document.Add(img); } } } return msDoc.ToArray(); } }
public override void ScreenShot(out String path) { base.ScreenShot(out path); var fs = FileSystem.OpenWrite(path, true); if (fs == null) { ConsoleWrapper.Print("SCR_ScreenShot_f: Couldn't create a file\n"); return; } using (var bmp = new Bitmap(Desc.ActualWidth, Desc.ActualHeight)) { var data = bmp.LockBits(new Rectangle(0, 0, Desc.ActualWidth, Desc.ActualHeight), System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format24bppRgb); GL.ReadPixels(0, 0, Desc.ActualWidth, Desc.ActualHeight, PixelFormat.Bgr, PixelType.UnsignedByte, data.Scan0); bmp.UnlockBits(data); bmp.RotateFlip(RotateFlipType.RotateNoneFlipY); var encoder = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders( ).First(c => c.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid); var encParams = new System.Drawing.Imaging.EncoderParameters( ) { Param = new[] { new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L) } }; bmp.Save(fs, encoder, encParams); } ConsoleWrapper.Print("Wrote {0}\n", Path.GetFileName(path)); }
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); }
protected static void ImageResize(System.Drawing.Image orjinalFoto, int boyut, string dosyaAdi, string filePath) { 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; 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(filePath + dosyaAdi), codec, eParams); }
/// <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); }
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); } }
public void KucukBoyut(System.Drawing.Image yuklenenFoto, int resimBoyutu, string resimIsmi) { System.Drawing.Bitmap islenmisFoto = null; System.Drawing.Graphics grafikNesnesi = null; int hedeflenenGenislik = resimBoyutu; int hedeflenenYukseklik = resimBoyutu; int yeni_gen, yeni_yuk; yeni_yuk = (int)Math.Round(((float)yuklenenFoto.Height * (float)resimBoyutu) / (float)yuklenenFoto.Width); yeni_gen = hedeflenenGenislik; hedeflenenYukseklik = yeni_yuk; yeni_gen = yeni_gen > hedeflenenGenislik ? hedeflenenGenislik : yeni_gen; yeni_yuk = yeni_yuk > hedeflenenYukseklik ? hedeflenenYukseklik : yeni_yuk; islenmisFoto = new System.Drawing.Bitmap(hedeflenenGenislik, hedeflenenYukseklik); grafikNesnesi = System.Drawing.Graphics.FromImage(islenmisFoto); grafikNesnesi.FillRectangle(new System.Drawing.SolidBrush(System.Drawing.Color.White), new System.Drawing.Rectangle(0, 0, hedeflenenGenislik, hedeflenenYukseklik)); int x = (hedeflenenGenislik - yeni_gen) / 2; int y = (hedeflenenYukseklik - yeni_yuk) / 2; grafikNesnesi.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; grafikNesnesi.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; grafikNesnesi.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); grafikNesnesi.DrawImage(yuklenenFoto, x, y, yeni_gen, yeni_yuk); islenmisFoto.Save(Server.MapPath("/Content/" + resimIsmi), codec, eParams); }
public static string GetJPEGBase64StringFromBitmapImage(BitmapImage bmpImage, long jpegEncoderQuality, System.Drawing.RotateFlipType rotateFlip) { System.Drawing.Bitmap bmp = null; MemoryStream ms = new MemoryStream(); try { System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(myEncoder, jpegEncoderQuality); System.Drawing.Imaging.ImageCodecInfo jgpEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); bmp = UIHelper.BitmapImage2Bitmap(bmpImage); bmp.RotateFlip(rotateFlip); bmp.Save(ms, jgpEncoder, encoderParameters); return(Convert.ToBase64String(ms.ToArray())); } finally { DeleteObject(bmp.GetHbitmap()); bmp.Dispose(); bmp = null; } }
public static void Thumbize(string pPage, string pThumb, Document document, Page page) { System.IO.MemoryStream cryptoStream = new System.IO.MemoryStream(Utility.Security.AES.DecryptStream(page.Token, System.IO.File.ReadAllBytes(System.IO.Path.Combine(pPage, page.Filename))).ToArray()); using (var srcImage = System.Drawing.Image.FromStream(cryptoStream)) { var newWidth = 300; var newHeight = 200; using (var newImage = new Bitmap(newWidth, newHeight)) using (var graphics = Graphics.FromImage(newImage)) { graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; graphics.DrawImage(srcImage, new System.Drawing.Rectangle(0, 0, newWidth, newHeight)); System.IO.MemoryStream ms = new System.IO.MemoryStream(); 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 = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.FormatDescription == "JPEG"); newImage.Save(ms, jpegEncoder, parms); System.IO.File.WriteAllBytes(System.IO.Path.Combine(pThumb, string.Format("{0}.jpg", document.Id.ToString())), SoftFluent.Samples.GED.Utility.Security.AES.EncryptStream(document.Token, ms.ToArray()).ToArray()); ms.Close(); } } }
/**/ /// <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 WriteBMP(Bitmap bmp, string filename, DateTime datetimeutc) { using (var memstream = new MemoryStream()) { if (OutputFileExtension == OutputTypes.jpg) { var encodeparams = new System.Drawing.Imaging.EncoderParameters(); encodeparams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, Quality); bmp.Save(memstream, GetCodec(System.Drawing.Imaging.ImageFormat.Jpeg), encodeparams); } else if (OutputFileExtension == OutputTypes.tiff) { bmp.Save(memstream, System.Drawing.Imaging.ImageFormat.Tiff); } else if (OutputFileExtension == OutputTypes.bmp) { bmp.Save(memstream, System.Drawing.Imaging.ImageFormat.Bmp); } else { bmp.Save(memstream, System.Drawing.Imaging.ImageFormat.Png); } File.WriteAllBytes(filename, memstream.ToArray()); File.SetCreationTime(filename, datetimeutc); } }
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 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); } }
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(); } }
public static System.Drawing.Imaging.EncoderParameters GetEncoderParameters() { System.Drawing.Imaging.EncoderParameters parameters1 = new System.Drawing.Imaging.EncoderParameters(3); parameters1.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 2L); parameters1.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L); parameters1.Param[2] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 24L); return parameters1; }
public static void writeToFile(COMMON.ByteMatrix matrix, System.Drawing.Imaging.ImageFormat format, string file) { System.Drawing.Imaging.EncoderParameters eps = new System.Drawing.Imaging.EncoderParameters(); eps.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); Bitmap bmap = toBitmap(matrix); bmap.Save(file, format); }
public static System.Drawing.Imaging.EncoderParameters GetEncoderParameters() { System.Drawing.Imaging.EncoderParameters parameters1 = new System.Drawing.Imaging.EncoderParameters(3); parameters1.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, 2L); parameters1.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L); parameters1.Param[2] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 24L); return(parameters1); }
public static void ExtractImagesFromPDF(string password, string key, string docPath, string pagePath, PageCollection pages) { Page page = null; // NOTE: This will only get the first image it finds per page. PdfReader pdf = new PdfReader(Utility.Security.AES.DecryptFile(key, docPath)); //RandomAccessFileOrArray raf = new iTextSharp.text.pdf.RandomAccessFileOrArray(p); 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 = System.Drawing.Image.FromStream(memStream); // must save the file while stream is open. page = new Page(); page.Order = pages.Count; page.Save(); page.Token = Utility.Security.AES.GetToken(page.Id, password); //string path = System.IO.Path.Combine(page.Filename, 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 = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.FormatDescription == "JPEG"); System.IO.MemoryStream ms = new System.IO.MemoryStream(); img.Save(ms, jpegEncoder, parms); System.IO.File.WriteAllBytes(System.IO.Path.Combine(pagePath, page.Filename), SoftFluent.Samples.GED.Utility.Security.AES.EncryptStream(page.Token, ms.ToArray()).ToArray()); ms.Close(); pages.Add(page); } } } } } catch { throw; } finally { pdf.Close(); //raf.Close(); } }
private static void BitmapToJPEG(Bitmap objBitmap, string strFilename, long lngCompression) { System.Drawing.Imaging.EncoderParameters objEncoderParameters; System.Drawing.Imaging.ImageCodecInfo objImageCodecInfo; objEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1); 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 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); }
private static System.Drawing.Image SaveImages( System.Drawing.Imaging.ImageCodecInfo tiffCodec , System.IO.MemoryStream outputStream , System.Drawing.Image tiffImage, System.Drawing.Image firstImage) { using (System.Drawing.Imaging.EncoderParameters encParameters = new System.Drawing.Imaging.EncoderParameters(3)) { if (firstImage == null) { encParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.SaveFlag , (long)System.Drawing.Imaging.EncoderValue.MultiFrame // 18L ); } else { encParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.SaveFlag , (long)System.Drawing.Imaging.EncoderValue.FrameDimensionPage // 23L ); } encParameters.Param[1] = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.ColorDepth, 24L ); encParameters.Param[2] = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.Compression , (long)System.Drawing.Imaging.EncoderValue.CompressionLZW ); if (firstImage == null) { firstImage = tiffImage; ((System.Drawing.Bitmap)tiffImage).SetResolution(96, 96); firstImage.Save(outputStream, tiffCodec, encParameters); } else { ((System.Drawing.Bitmap)tiffImage).SetResolution(96, 96); firstImage.SaveAdd(tiffImage, encParameters); } if (encParameters.Param[0] != null) { encParameters.Param[0].Dispose(); } if (encParameters.Param[1] != null) { encParameters.Param[1].Dispose(); } if (encParameters.Param[2] != null) { encParameters.Param[2].Dispose(); } } // End Using encParameters return(firstImage); }
private void MakeThumbnail() { using (Image img = new Bitmap(_filePath)) { Size newSize = GenerateImageDimensions(img.Width, img.Height, _maxWidth, _maxHeight); int imgWidth = newSize.Width; int imgHeight = newSize.Height; // create the thumbnail image using (Image img2 = img.GetThumbnailImage(imgWidth, imgHeight, new Image.GetThumbnailImageAbort(Abort), IntPtr.Zero)) { using (Graphics g = Graphics.FromImage(img2)) // 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; //BMP 0, JPEG 1 , GIF 2 , TIFF 3, PNG 4 System.Drawing.Imaging.ImageCodecInfo codec; switch (Path.GetExtension(_filePath)) { case ".gif": codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[2]; ImageFormat = System.Drawing.Imaging.ImageFormat.Gif; MimeType = "image/gif"; break; case ".png": codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[4]; ImageFormat = System.Drawing.Imaging.ImageFormat.Png; MimeType = "image/png"; break; default: //jpg codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1]; ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg; MimeType = "image/jpg"; break; } //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, 90L); //Now draw the image on the instance of thumbnail Bitmap object g.DrawImage(img, new Rectangle(0, 0, img2.Width, img2.Height)); MemoryStream ms = new MemoryStream(); img2.Save(ms, codec, eParams); ImageBytes = new byte[ms.Length]; ImageBytes = ms.ToArray(); ms.Close(); ms.Dispose(); } } } }
public static byte[] MakeClearlyImage(string originalImagePath, long p = 30) { MemoryStream stream = new MemoryStream(); //获取原始图片 System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath); //新建一个bmp图片,并设置缩略图大小. System.Drawing.Image bitmap = new System.Drawing.Bitmap(originalImage.Width, originalImage.Height); //新建一个画板 System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并设置背景色 g.Clear(System.Drawing.Color.FromArgb(100, 255, 255, 255)); //在指定位置并且按指定大小绘制原图片的指定部分 //第一个System.Drawing.Rectangle是原图片的画布坐标和宽高,第二个是原图片写在画布上的坐标和宽高,最后一个参数是指定数值单位为像素 g.DrawImage(originalImage, new System.Drawing.Point() { X = 0, Y = 0 }); System.Drawing.Imaging.ImageCodecInfo encoder = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().FirstOrDefault(a => a.MimeType == "image/jpeg"); try { if (encoder != null) { System.Drawing.Imaging.EncoderParameters encoderParams = new System.Drawing.Imaging.EncoderParameters(1); //设置 jpeg 质量为 60 encoderParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, p); bitmap.Save(stream, encoder, encoderParams); encoderParams.Dispose(); return(stream.ToArray()); } } catch (System.Exception e) { new TxtLogHelper().Error(e); throw e; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } return(null); }
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 static void SaveJPEG(this Bitmap a_bitmap, Stream a_stream, int a_quality) { Debug.Assert(a_quality > 0); Debug.Assert(a_quality <= 100); var eps = new System.Drawing.Imaging.EncoderParameters(1); eps.Param[0] = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.Quality, (long)a_quality); a_bitmap.Save(a_stream, System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders().FirstOrDefault( c => c.FormatID == System.Drawing.Imaging.ImageFormat.Jpeg.Guid), eps); }
/// <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 Image Resize(this Image source, int canvasWidth, int canvasHeight) { var originalWidth = source.Width; var originalHeight = source.Height; if(canvasHeight == originalHeight && canvasWidth == originalWidth) { return source; } System.Drawing.Image thumbnail = new Bitmap(canvasWidth, canvasHeight); System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(thumbnail); graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; graphic.SmoothingMode = SmoothingMode.HighQuality; graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; graphic.CompositingQuality = CompositingQuality.HighQuality; // Figure out the ratio double ratioX = (double)canvasWidth / (double)originalWidth; double ratioY = (double)canvasHeight / (double)originalHeight; // use whichever multiplier is smaller double ratio = ratioX < ratioY ? ratioX : ratioY; // now we can get the new height and width int newHeight = Convert.ToInt32(originalHeight * ratio); int newWidth = Convert.ToInt32(originalWidth * ratio); // Now calculate the X,Y position of the upper-left corner // (one of these will always be zero) int posX = Convert.ToInt32((canvasWidth - (originalWidth * ratio)) / 2); int posY = Convert.ToInt32((canvasHeight - (originalHeight * ratio)) / 2); graphic.Clear(Color.Black); // white padding graphic.DrawImage(source, posX, posY, newWidth, newHeight); System.Drawing.Imaging.ImageCodecInfo[] info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.EncoderParameters encoderParameters; encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); return thumbnail; }
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; }
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"); } } } }
public static string GetJPEGBase64StringFromBitmapImage(BitmapImage bmpImage, long jpegEncoderQuality, System.Drawing.RotateFlipType rotateFlip) { System.Drawing.Bitmap bmp = null; MemoryStream ms = new MemoryStream(); try { System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(myEncoder, jpegEncoderQuality); System.Drawing.Imaging.ImageCodecInfo jgpEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg); bmp = UIHelper.BitmapImage2Bitmap(bmpImage); bmp.RotateFlip(rotateFlip); bmp.Save(ms, jgpEncoder, encoderParameters); return Convert.ToBase64String(ms.ToArray()); } finally { DeleteObject(bmp.GetHbitmap()); bmp.Dispose(); bmp = null; } }
/// <summary> /// 正方型裁剪 /// 以图片中心为轴心,截取正方型,然后等比缩放 /// 用于头像处理 /// </summary> /// <param name="fromFile">原图Stream对象</param> /// <param name="fileSaveUrl">缩略图存放地址</param> /// <param name="side">指定的边长(正方型)</param> /// <param name="quality">质量(范围0-100)</param> public static void CutForSquare(System.IO.Stream fromFile, string fileSaveUrl, int side, int quality) { //创建目录 DME_Files.InitFolder(DME_Path.GetDirectoryName(fileSaveUrl)); //原始图片(获取原始图片创建对象,并使用流中嵌入的颜色管理信息) System.Drawing.Image initImage = System.Drawing.Image.FromStream(fromFile, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= side && initImage.Height <= side) { initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //原始图片的宽、高 int initWidth = initImage.Width; int initHeight = initImage.Height; //非正方型先裁剪为正方型 if (initWidth != initHeight) { //截图对象 System.Drawing.Image pickedImage = null; System.Drawing.Graphics pickedG = null; //宽大于高的横图 if (initWidth > initHeight) { //对象实例化 pickedImage = new System.Drawing.Bitmap(initHeight, initHeight); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //定位 System.Drawing.Rectangle fromR = new System.Drawing.Rectangle((initWidth - initHeight) / 2, 0, initHeight, initHeight); System.Drawing.Rectangle toR = new System.Drawing.Rectangle(0, 0, initHeight, initHeight); //画图 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //重置宽 initWidth = initHeight; } //高大于宽的竖图 else { //对象实例化 pickedImage = new System.Drawing.Bitmap(initWidth, initWidth); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //定位 System.Drawing.Rectangle fromR = new System.Drawing.Rectangle(0, (initHeight - initWidth) / 2, initWidth, initWidth); System.Drawing.Rectangle toR = new System.Drawing.Rectangle(0, 0, initWidth, initWidth); //画图 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //重置高 initHeight = initWidth; } //将截图对象赋给原图 initImage = (System.Drawing.Image)pickedImage.Clone(); //释放截图资源 pickedG.Dispose(); pickedImage.Dispose(); } //缩略图对象 System.Drawing.Image resultImage = new System.Drawing.Bitmap(side, side); System.Drawing.Graphics resultG = System.Drawing.Graphics.FromImage(resultImage); //设置质量 resultG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; resultG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //用指定背景色清空画布 resultG.Clear(System.Drawing.Color.White); //绘制缩略图 resultG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, side, side), new System.Drawing.Rectangle(0, 0, initWidth, initHeight), System.Drawing.GraphicsUnit.Pixel); //关键质量控制 //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff System.Drawing.Imaging.ImageCodecInfo[] icis = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.ImageCodecInfo ici = null; foreach (System.Drawing.Imaging.ImageCodecInfo i in icis) { if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif") { ici = i; } } 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)quality); //保存缩略图 resultImage.Save(fileSaveUrl, ici, ep); //释放关键质量控制所用资源 ep.Dispose(); //释放缩略图资源 resultG.Dispose(); resultImage.Dispose(); //释放原始图片资源 initImage.Dispose(); } }
/// <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(); } }
public void SaveBarcodeExec() { try { using (PrinterX myPrinter = new PrinterX()) { string DocumentName = String.Format("{0}_{1}_{2}.tif", CurrentBarcodeInfo.PrimaryBarcodeValue, CurrentBarcodeInfo.SecondaryBarcodeValue, DateTime.Now.ToString("yyyyMMddhhmmss")); // Let factory create the IOpenFileDialog IFolderBrowserDialog folderBrowserDialog = folderBrowserDialogFactory(); folderBrowserDialog.Description = "Choose Folder"; folderBrowserDialog.ShowNewFolderButton = true; // Open the dialog System.Windows.Forms.DialogResult result = dialogService.ShowFolderBrowserDialog(this, folderBrowserDialog); if (result == System.Windows.Forms.DialogResult.OK) { System.Drawing.Imaging.ImageCodecInfo codecInfo = getCodecForstring("TIFF"); System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1); ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, Convert.ToInt32(System.Drawing.Imaging.EncoderValue.CompressionCCITT4)); CurrentBarcodeImage.Save(Path.Combine(folderBrowserDialog.SelectedPath, DocumentName), codecInfo, ep); } } } catch (Exception ex) { HandleErrorMessage(ex); } }
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."); }
/// <summary> /// 指定长宽裁剪 /// 按模版比例最大范围的裁剪图片并缩放至模版尺寸 /// </summary> /// <param name="postedFile">原图HttpPostedFile对象</param> /// <param name="fileSaveUrl">保存路径</param> /// <param name="maxWidth">最大宽(单位:px)</param> /// <param name="maxHeight">最大高(单位:px)</param> /// <param name="quality">质量(范围0-100)</param> public static void CutForCustom(System.Web.HttpPostedFile postedFile, string fileSaveUrl, int maxWidth, int maxHeight, int quality) { //创建目录 DME_Files.InitFolder(DME_Path.GetDirectoryName(fileSaveUrl)); //从文件获取原始图片,并使用流中嵌入的颜色管理信息 System.Drawing.Image initImage = System.Drawing.Image.FromStream(postedFile.InputStream, true); //原图宽高均小于模版,不作处理,直接保存 if (initImage.Width <= maxWidth && initImage.Height <= maxHeight) { initImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); } else { //模版的宽高比例 double templateRate = (double)maxWidth / maxHeight; //原图片的宽高比例 double initRate = (double)initImage.Width / initImage.Height; //原图与模版比例相等,直接缩放 if (templateRate == initRate) { //按模版大小生成最终图片 System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight); System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage); templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(System.Drawing.Color.White); templateG.DrawImage(initImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, initImage.Width, initImage.Height), System.Drawing.GraphicsUnit.Pixel); templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); } //原图与模版比例不等,裁剪后缩放 else { //裁剪对象 System.Drawing.Image pickedImage = null; System.Drawing.Graphics pickedG = null; //定位 System.Drawing.Rectangle fromR = new System.Drawing.Rectangle(0, 0, 0, 0);//原图裁剪定位 System.Drawing.Rectangle toR = new System.Drawing.Rectangle(0, 0, 0, 0);//目标定位 //宽为标准进行裁剪 if (templateRate > initRate) { //裁剪对象实例化 pickedImage = new System.Drawing.Bitmap(initImage.Width, (int)Math.Floor(initImage.Width / templateRate)); pickedG = System.Drawing.Graphics.FromImage(pickedImage); //裁剪源定位 fromR.X = 0; fromR.Y = (int)Math.Floor((initImage.Height - initImage.Width / templateRate) / 2); fromR.Width = initImage.Width; fromR.Height = (int)Math.Floor(initImage.Width / templateRate); //裁剪目标定位 toR.X = 0; toR.Y = 0; toR.Width = initImage.Width; toR.Height = (int)Math.Floor(initImage.Width / templateRate); } //高为标准进行裁剪 else { pickedImage = new System.Drawing.Bitmap((int)Math.Floor(initImage.Height * templateRate), initImage.Height); pickedG = System.Drawing.Graphics.FromImage(pickedImage); fromR.X = (int)Math.Floor((initImage.Width - initImage.Height * templateRate) / 2); fromR.Y = 0; fromR.Width = (int)Math.Floor(initImage.Height * templateRate); fromR.Height = initImage.Height; toR.X = 0; toR.Y = 0; toR.Width = (int)Math.Floor(initImage.Height * templateRate); toR.Height = initImage.Height; } //设置质量 pickedG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; pickedG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //裁剪 pickedG.DrawImage(initImage, toR, fromR, System.Drawing.GraphicsUnit.Pixel); //按模版大小生成最终图片 System.Drawing.Image templateImage = new System.Drawing.Bitmap(maxWidth, maxHeight); System.Drawing.Graphics templateG = System.Drawing.Graphics.FromImage(templateImage); templateG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; templateG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; templateG.Clear(System.Drawing.Color.White); templateG.DrawImage(pickedImage, new System.Drawing.Rectangle(0, 0, maxWidth, maxHeight), new System.Drawing.Rectangle(0, 0, pickedImage.Width, pickedImage.Height), System.Drawing.GraphicsUnit.Pixel); //关键质量控制 //获取系统编码类型数组,包含了jpeg,bmp,png,gif,tiff System.Drawing.Imaging.ImageCodecInfo[] icis = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.ImageCodecInfo ici = null; foreach (System.Drawing.Imaging.ImageCodecInfo i in icis) { if (i.MimeType == "image/jpeg" || i.MimeType == "image/bmp" || i.MimeType == "image/png" || i.MimeType == "image/gif") { ici = i; } } 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)quality); //保存缩略图 templateImage.Save(fileSaveUrl, ici, ep); //templateImage.Save(fileSaveUrl, System.Drawing.Imaging.ImageFormat.Jpeg); //释放资源 templateG.Dispose(); templateImage.Dispose(); pickedG.Dispose(); pickedImage.Dispose(); } } //释放资源 initImage.Dispose(); }
private void make_thm(int width, int height, bool fix_ar, string format) { Bitmap bmp = null; Graphics g = null; AviSynthReader reader = null; string new_script = m.script; string thmpath = Calculate.RemoveExtention(m.outfilepath) + format; SetLog("CREATING THM"); SetLog("------------------------------"); SetLog("Saving picture to: " + thmpath); SetLog(format.ToUpper() + " " + width + "x" + height + " \r\n"); try { if (fix_ar) { int crop_w = 0, crop_h = 0; double old_asp = m.outaspect; double new_asp = (double)width / (double)height; if (old_asp < new_asp) { crop_h = Math.Max(Convert.ToInt32((m.outresh - ((m.outresh * old_asp) / new_asp)) / 2), 0); } else if (old_asp > new_asp) { crop_w = Math.Max(Convert.ToInt32((m.outresw - (m.outresw / old_asp) * new_asp) / 2), 0); } new_script += ("Lanczos4Resize(" + width + ", " + height + ", " + crop_w + ", " + crop_h + ", -" + crop_w + ", -" + crop_h + ")\r\n"); } reader = new AviSynthReader(AviSynthColorspace.RGB24, AudioSampleType.Undefined); reader.ParseScript(new_script); //проверка на выходы за пределы общего количества кадров int frame = (m.thmframe > reader.FrameCount) ? reader.FrameCount / 2 : m.thmframe; if (width == reader.Width && height == reader.Height) { bmp = new System.Drawing.Bitmap(reader.ReadFrameBitmap(frame)); } else { bmp = new Bitmap(width, height); g = Graphics.FromImage(bmp); //метод интерполяции при ресайзе g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(reader.ReadFrameBitmap(frame), 0, 0, width, height); } if (format == "jpg") { //процент cжатия jpg System.Drawing.Imaging.ImageCodecInfo[] info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L); //jpg bmp.Save(thmpath, info[1], encoderParameters); } else if (format == "png") { //png bmp.Save(thmpath, System.Drawing.Imaging.ImageFormat.Png); } else { //bmp bmp.Save(thmpath, System.Drawing.Imaging.ImageFormat.Bmp); } } catch (Exception ex) { SetLog("\r\nError creating THM: " + ex.Message.ToString() + Environment.NewLine); } finally { //завершение if (g != null) { g.Dispose(); g = null; } if (bmp != null) { bmp.Dispose(); bmp = null; } if (reader != null) { reader.Close(); reader = null; } SetLog(""); } }
/// <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(); }
/// <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 string SmartResizeImageAndUpload(FileUpload FileUpload1, string dir_path, double maxWidth, double maxHeight) { string file_name = System.IO.Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName); string file_ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower().Trim(); string file_name_ext = file_name + file_ext; string encoded_image = GetEncodeString(file_name) + file_ext; try { // Declare variable for the conversion float ratio; // Create variable to hold the image string filepath = dir_path + "/" + encoded_image; FileUpload1.SaveAs(Server.MapPath(filepath)); System.Drawing.Image myimage = System.Drawing.Image.FromFile(Server.MapPath(filepath)); // Get height and width of current image int width = (int)myimage.Width; int height = (int)myimage.Height; // Ratio and conversion for new size if (width > maxWidth) { ratio = (float)width / (float)maxWidth; width = (int)(width / ratio); height = (int)(height / ratio); } // Ratio and conversion for new size if (height > maxHeight) { ratio = (float)height / (float)maxHeight; height = (int)(height / ratio); width = (int)(width / ratio); } System.Drawing.Bitmap source_bitmap = new System.Drawing.Bitmap(myimage); myimage.Dispose(); System.Drawing.Bitmap thumb_bitmap = new System.Drawing.Bitmap(width, height); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(thumb_bitmap); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle(System.Drawing.Brushes.White, 0, 0, width, height); g.DrawImage(source_bitmap, 0, 0, width, height); g.Dispose(); System.Drawing.Imaging.ImageCodecInfo[] Info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.EncoderParameters Params = new System.Drawing.Imaging.EncoderParameters(1); Params.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); thumb_bitmap.Save(Server.MapPath(filepath), Info[1], Params); } catch (Exception ex) { ex.Message.ToString(); } return encoded_image; }
// http://dobon.net/vb/dotnet/graphics/createmultitiff.html bool tiffconcat(List<string> files, string output) { tempFilesDeleter.AddFile(output); var Compression = System.Drawing.Imaging.EncoderValue.CompressionLZW; if (files.Count == 0) return true; if (files.Count == 1) { File.Copy(Path.Combine(workingDir, files[0]), Path.Combine(workingDir, output)); } else { System.Drawing.Imaging.ImageCodecInfo ici = null; foreach (var enc in System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()) { if (enc.MimeType == "image/tiff") { ici = enc; break; } } if (ici == null) { if (controller_ != null) controller_.appendOutput(Properties.Resources.FAIL_CONCAT_IMAGES); return false; } var bitmaps = files.Select(f => new System.Drawing.Bitmap(Path.Combine(workingDir, f))).ToList(); try { using (var ep = new System.Drawing.Imaging.EncoderParameters(2)) { ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.MultiFrame); ep.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)Compression); bitmaps[0].Save(Path.Combine(workingDir, output), ici, ep); } for (int i = 1; i < files.Count; ++i) { using (var ep = new System.Drawing.Imaging.EncoderParameters(2)) { ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.FrameDimensionPage); ep.Param[1] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)Compression); bitmaps[0].SaveAdd(bitmaps[i], ep); } } using (var ep = new System.Drawing.Imaging.EncoderParameters(1)) { ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, (long)System.Drawing.Imaging.EncoderValue.Flush); bitmaps[0].SaveAdd(ep); } } finally { foreach (var b in bitmaps) b.Dispose(); } } if (File.Exists(Path.Combine(workingDir, output))) { if (controller_ != null) controller_.appendOutput("TeX2img: Concatinate TIFF files"); return true; } else return false; }
public string ResizeImageAndUpload(FileUpload FileUpload1, string dir_path, int height, int width) { string file_name = System.IO.Path.GetFileNameWithoutExtension(FileUpload1.PostedFile.FileName); string file_ext = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower().Trim(); string file_name_ext = file_name + file_ext; string encoded_image = GetEncodeString(file_name) + file_ext; try { //string filename = FileUpload1.FileName; string filepath = dir_path + "/" + encoded_image; FileUpload1.SaveAs(Server.MapPath(filepath)); System.Drawing.Image myimage = System.Drawing.Image.FromFile(Server.MapPath(filepath)); System.Drawing.Bitmap source_bitmap = new System.Drawing.Bitmap(myimage); myimage.Dispose(); System.Drawing.Bitmap thumb_bitmap = new System.Drawing.Bitmap(width, height); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(thumb_bitmap); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.FillRectangle(System.Drawing.Brushes.White, 0, 0, width, height); g.DrawImage(source_bitmap, 0, 0, width, height); g.Dispose(); System.Drawing.Imaging.ImageCodecInfo[] Info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.EncoderParameters Params = new System.Drawing.Imaging.EncoderParameters(1); Params.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L); thumb_bitmap.Save(Server.MapPath(filepath), Info[1], Params); } catch (Exception ex) { ex.Message.ToString(); } return encoded_image; }
private void SavePicture(string path, int width, int height, bool fix_ar, int frame) { System.Drawing.Bitmap bmp = null; System.Drawing.Graphics g = null; AviSynthReader reader = null; string new_script = m.script; try { if (fix_ar && width != 0 && height != 0) { int crop_w = 0, crop_h = 0; double old_asp = m.outaspect; double new_asp = (double)width / (double)height; if (old_asp < new_asp) { crop_h = Math.Max(Convert.ToInt32((m.outresh - ((m.outresh * old_asp) / new_asp)) / 2), 0); } else if (old_asp > new_asp) { crop_w = Math.Max(Convert.ToInt32((m.outresw - (m.outresw / old_asp) * new_asp) / 2), 0); } new_script += ("Lanczos4Resize(" + width + ", " + height + ", " + crop_w + ", " + crop_h + ", -" + crop_w + ", -" + crop_h + ")\r\n"); } reader = new AviSynthReader(AviSynthColorspace.RGB24, AudioSampleType.Undefined); reader.ParseScript(new_script); if (width == 0 || height == 0 || (width == reader.Width && height == reader.Height)) { bmp = new System.Drawing.Bitmap(reader.ReadFrameBitmap(frame)); } else { bmp = new System.Drawing.Bitmap(width, height); g = System.Drawing.Graphics.FromImage(bmp); //метод интерполяции при ресайзе g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(reader.ReadFrameBitmap(frame), 0, 0, width, height); } string ext = Path.GetExtension(path).ToLower(); if (ext == ".jpg") { //процент cжатия jpg System.Drawing.Imaging.ImageCodecInfo[] info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders(); System.Drawing.Imaging.EncoderParameters encoderParameters = new System.Drawing.Imaging.EncoderParameters(1); encoderParameters.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 95L); //jpg bmp.Save(path, info[1], encoderParameters); } else if (ext == ".png") { //png bmp.Save(path, System.Drawing.Imaging.ImageFormat.Png); } else { //bmp bmp.Save(path, System.Drawing.Imaging.ImageFormat.Bmp); } } catch (Exception ex) { ErrorException("SavePicture: " + ex.Message, ex.StackTrace); } finally { //завершение if (g != null) { g.Dispose(); g = null; } if (bmp != null) { bmp.Dispose(); bmp = null; } if (reader != null) { reader.Close(); reader = null; } } }
/// <summary> /// 生成缩略图 /// </summary> private void MakeThumbnail() { Image originalImage = Image.FromFile(_webFilePath); Int32 towidth = _thumbnailWidth; Int32 toheight = _thumbnailHeight; Int32 x = 0; Int32 y = 0; Int32 ow = originalImage.Width; Int32 oh = originalImage.Height; if (ow < towidth && oh < toheight) originalImage.Save(_webThumbnailFilePath); else { switch (_thumbnailMode) { case ThumbnailMode.Hw: break; case ThumbnailMode.W: toheight = originalImage.Height * _thumbnailWidth / originalImage.Width; break; case ThumbnailMode.H: towidth = originalImage.Width * _thumbnailHeight / originalImage.Height; break; case ThumbnailMode.Cut: if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * _thumbnailHeight / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; case ThumbnailMode.Auto: if (ow > oh) toheight = (Int32)((double)oh / (double)ow * (double)towidth); else towidth = (Int32)((double)ow / (double)oh * (double)toheight); break; default: if (ow > oh) toheight = (Int32)((double)oh / (double)ow * (double)towidth); else towidth = (Int32)((double)ow / (double)oh * (double)toheight); break; } //进行缩图 Bitmap img = new Bitmap(towidth, toheight); img.SetResolution(72f, 72f); Graphics gdiobj = Graphics.FromImage(img); gdiobj.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; gdiobj.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; gdiobj.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; gdiobj.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; gdiobj.FillRectangle(new SolidBrush(Color.White), 0, 0, towidth, toheight); Rectangle destrect = new Rectangle(0, 0, towidth, toheight); gdiobj.DrawImage(originalImage, destrect, 0, 0, ow, oh, GraphicsUnit.Pixel); 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); System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg"); try { if (ici != null) img.Save(_webThumbnailFilePath, ici, ep); else img.Save(_webThumbnailFilePath, System.Drawing.Imaging.ImageFormat.Jpeg); } catch (Exception e) { throw new Exception(e.Message); } finally { gdiobj.Dispose(); img.Dispose(); } } originalImage.Dispose(); }