public void Dispose() { if (fSystemImage != null) { fSystemImage.Dispose(); fSystemImage = null; } }
public string HeadPic_Save() { HttpPostedFile f = context.Request.Files[0]; string empNo = this.GetRequestVal("EmpNo"); if (DataType.IsNullOrEmpty(empNo) == true) { empNo = WebUser.No; } try { string tempFile = BP.Sys.SystemConfig.PathOfWebApp + "/DataUser/UserIcon/" + empNo + ".png"; if (System.IO.File.Exists(tempFile) == true) { System.IO.File.Delete(tempFile); } f.SaveAs(tempFile); System.Drawing.Image img = System.Drawing.Image.FromFile(tempFile); img.Dispose(); } catch (Exception ex) { return("err@" + ex.Message); } return("上传成功!"); }
private WriteableBitmap GetAvatarWriteableBitmap(string path) { log.Info("Gat avatar writable bitmap"); if (!File.Exists(path)) { log.Info("Failed to get avatar writable bitmap for path not existed"); return(null); } if (null == path) { log.Info("Failed to get avatar writable bitmap for null path"); return(null); } try { System.Drawing.Image sourceImage = System.Drawing.Image.FromFile(path); int imageWidth = sourceImage.Width, imageHeight = sourceImage.Height; System.Drawing.Bitmap sourceBmp = new System.Drawing.Bitmap(sourceImage, imageWidth, imageHeight); IntPtr hBitmap = sourceBmp.GetHbitmap(); BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); bitmapSource.Freeze(); WriteableBitmap writeableBmp = new WriteableBitmap(bitmapSource); sourceImage.Dispose(); sourceBmp.Dispose(); return(writeableBmp); } catch (Exception e) { log.InfoFormat("Failed to get avatar writeable bitmap, exception:{0}", e); return(null); } }
public void GetMap_GeometryProvider_ReturnImage() { SharpMap.Map map = new SharpMap.Map(new System.Drawing.Size(400, 200)); SharpMap.Layers.VectorLayer vLayer = new SharpMap.Layers.VectorLayer("Geom layer", CreateDatasource()); vLayer.Style.Outline = new System.Drawing.Pen(System.Drawing.Color.Red, 2f); vLayer.Style.EnableOutline = true; vLayer.Style.Line = new System.Drawing.Pen(System.Drawing.Color.Green, 2f); vLayer.Style.Fill = System.Drawing.Brushes.Yellow; map.Layers.Add(vLayer); SharpMap.Layers.VectorLayer vLayer2 = new SharpMap.Layers.VectorLayer("Geom layer 2", vLayer.DataSource); vLayer2.Style.SymbolOffset = new System.Drawing.PointF(3, 4); vLayer2.Style.SymbolRotation = 45; vLayer2.Style.SymbolScale = 0.4f; map.Layers.Add(vLayer2); SharpMap.Layers.VectorLayer vLayer3 = new SharpMap.Layers.VectorLayer("Geom layer 3", vLayer.DataSource); vLayer3.Style.SymbolOffset = new System.Drawing.PointF(3, 4); vLayer3.Style.SymbolRotation = 45; map.Layers.Add(vLayer3); SharpMap.Layers.VectorLayer vLayer4 = new SharpMap.Layers.VectorLayer("Geom layer 4", vLayer.DataSource); vLayer4.Style.SymbolOffset = new System.Drawing.PointF(3, 4); vLayer4.Style.SymbolScale = 0.4f; vLayer4.ClippingEnabled = true; map.Layers.Add(vLayer4); map.ZoomToExtents(); System.Drawing.Image img = map.GetMap(); Assert.IsNotNull(img); map.Dispose(); img.Dispose(); }
private void LoadImageFromPath(string path) { Image img = Image.FromFile(path); using (MemoryStream ms = new MemoryStream()) { img.Save(ms, System.Drawing.Imaging.ImageFormat.Png); ms.Position = 0; BitmapImage bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.StreamSource = ms; bi.EndInit(); if (CustomCards.Find(e => e.CardName == Path.GetFileName(path)) != null) { CustomCards.Find(e => e.CardName == Path.GetFileName(path)).Amount++; } else { CustomCards.Add(new CustomCard() { Amount = 1, CardName = Path.GetFileName(path), CardImage = ms.ToArray(), Directory = Path.GetDirectoryName(path) }); } img.Dispose(); } }
private void FillImageInfo(Stream fileStream, ref Services.FileSystem.FileInfo fileInfo) { var imageExtensions = new FileExtensionWhitelist(Common.Globals.glbImageFileTypes); if (imageExtensions.IsAllowedExtension(fileInfo.Extension)) { System.Drawing.Image img = null; try { img = System.Drawing.Image.FromStream(fileStream); fileInfo.Size = fileStream.Length > int.MaxValue ? int.MaxValue : int.Parse(fileStream.Length.ToString(CultureInfo.InvariantCulture)); fileInfo.Width = img.Width; fileInfo.Height = img.Height; } catch { // error loading image file fileInfo.ContentType = "application/octet-stream"; } finally { if (img != null) { img.Dispose(); } } } }
private void SendPicture_MouseDown(object sender, MouseButtonEventArgs e) { if (ofd == null) { ofd = new OpenFileDialog { Title = "Open a image file for sending", Filter = "Normal image format|*.jpg;*.jpeg;*.png;*.gif;*.bmp|JPEG|*.jpg;*.jpeg|PNG|*.png|GIF|*.gif|Bitmap|*.bmp|Other|*.*", CheckFileExists = true, Multiselect = false }; } if (ofd.ShowDialog().GetValueOrDefault(false)) { System.Drawing.Image imgForSending = null; try { imgForSending = System.Drawing.Image.FromFile(ofd.FileName); SendImage(imgForSending); } catch { MessageBox.Show("图片发送失败"); } finally { if (imgForSending != null) { imgForSending.Dispose(); } } } } // 发送图片 按钮按下 (打开文件框)
static public void UpdatePhotoSize(string filePath) { bool OK = false; for (int i = 0; i < _AVAILABLE_PHOTO_TYPE.Length; ++i) { if (filePath.ToLower().EndsWith(_AVAILABLE_PHOTO_TYPE[i])) { OK = true; break; } } if (!OK) { return; } if (!System.IO.File.Exists(filePath)) { return; } string fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1); System.Drawing.Image img = System.Drawing.Image.FromFile(filePath); if (img.Width > 0 && img.Height > 0) { // UpdatePhotoSize(fileName, img.Width, img.Height); img.Dispose(); } }
/// <summary> /// 生成缩略图 /// </summary> /// <param name="originalImagePath">源图路径(物理路径)</param> /// <param name="thumbnailPath">缩略图路径(物理路径)</param> /// <param name="width">缩略图宽度</param> /// <param name="height">缩略图高度</param> /// <param name="mode">生成缩略图的方式 /// <code>HW:指定高宽缩放(可能变形)</code> /// <code>W:指定宽,高按比例 </code> /// <code>H:指定高,宽按比例</code> /// <code>CUT:指定高宽裁减(不变形) </code> /// <code>FILL:填充</code> /// </param> public static bool LocalImage2Thumbs(string originalImagePath, string thumbnailPath, int width, int height, string mode) { System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath); Image2Thumbs(originalImage, thumbnailPath, width, height, mode); originalImage.Dispose(); return(true); }
private static void ConvertImage(String f, String destinationBasePath, Int32 counter, Int32 maxImageWidth) { String fName = System.IO.Path.GetFileName(f); String extension = System.IO.Path.GetExtension(fName); String finalPath = System.IO.Path.Combine(destinationBasePath, String.Format("{0}{1}", counter.ToString(), extension)); System.Drawing.Image img = System.Drawing.Image.FromFile(f); Double aspectRatio = (double)img.Height / (double)img.Width; Int32 newX, newY; if (img.Width > maxImageWidth) { newX = maxImageWidth; newY = (Int32)(newX * aspectRatio); } else { newX = img.Width; newY = img.Height; } Console.WriteLine(String.Format("{0} {1} {2}", newX, newY, aspectRatio)); Console.WriteLine("Beginning convert: " + fName); using (var resized = ImageUtilities.ResizeImage(img, newX, newY)) { Console.WriteLine("Converted: " + fName); //save the resized image as a jpeg with a quality of 90 ImageUtilities.SaveJpeg(finalPath, resized, 100); Console.WriteLine("Saved: " + finalPath); } img.Dispose(); }
/// <summary> /// 转换图片格式 /// </summary> /// <param name="originalBase64">源图片Base64</param> /// <param name="newFormat">图片输出格式</param> /// <returns>新图片流</returns> public static Stream FormatPicture(string originalBase64, PictureFormat newFormat) { char[] charBuffer = originalBase64.ToCharArray(); byte[] bytes = Convert.FromBase64CharArray(charBuffer, 0, charBuffer.Length); System.Drawing.Image originalImage = System.Drawing.Image.FromStream(new MemoryStream(bytes)); System.Drawing.Imaging.ImageFormat imageFormat = GetImageFormat(newFormat); System.IO.MemoryStream newStream = new MemoryStream(); try { //以指定格式保存图片 string outputFile = Path.GetTempPath() + Guid.NewGuid().ToString() + "." + newFormat.ToString(); originalImage.Save(outputFile, imageFormat); FileStream fs = File.Open(outputFile, FileMode.Open); newStream = new MemoryStream(ConvertStream.ToBuffer(fs)); fs.Close(); File.Delete(outputFile); } catch (Exception ex) { throw ex; } finally { originalImage.Dispose(); } return(newStream); }
/// <summary> /// 转换图片格式 /// </summary> /// <param name="originalStream">源图片流</param> /// <param name="newFormat">图片输出格式</param> /// <returns>新图片流</returns> public static Stream FormatPicture(Stream originalStream, PictureFormat newFormat) { System.Drawing.Image originalImage = System.Drawing.Image.FromStream(originalStream); System.Drawing.Imaging.ImageFormat imageFormat = GetImageFormat(newFormat); System.IO.MemoryStream newStream = new MemoryStream(); try { //以指定格式保存图片 string outputFile = Path.GetTempPath() + Guid.NewGuid().ToString() + ".png"; originalImage.Save(outputFile, imageFormat); FileStream fs = File.Open(outputFile, FileMode.Open); newStream = new MemoryStream(ConvertStream.ToBuffer(fs)); fs.Close(); File.Delete(outputFile); } catch (Exception ex) { throw ex; } finally { originalImage.Dispose(); } return(newStream); }
/// <summary> /// 传入一个带绝对路径的图片文件,返回图片高度 /// </summary> /// <param name="strPic"></param> /// <returns></returns> public static int[] GetImageWidthHeight(string strPic) { System.Drawing.Image MyImage = System.Drawing.Image.FromFile(strPic); int[] arrint = { MyImage.Width, MyImage.Height }; MyImage.Dispose(); return(arrint); }
public static Texture2DArray GifToTextureArray(string path) { Texture2DArray array = null; #if DOT_NET_TWO_POINT_ZERO_OR_ABOVE #if IMAGING_DLL_EXISTS EditorUtility.DisplayProgressBar("Creating Texture Array for " + path, "", 0); System.Drawing.Image IMG = System.Drawing.Image.FromFile(path); int Length = IMG.GetFrameCount(FrameDimension.Time); IMG.SelectActiveFrame(FrameDimension.Time, 0); array = new Texture2DArray(IMG.Width, IMG.Height, Length, TextureFormat.RGBA32, true, false); for (int i = 0; i < Length; i++) { EditorUtility.DisplayProgressBar("Creating Texture Array for " + path, "Converting frame #" + i, (float)i / Length); IMG.SelectActiveFrame(FrameDimension.Time, i); System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(IMG); MemoryStream msFinger = new MemoryStream(); IMG.Save(msFinger, bitmap.RawFormat); Texture2D texture = new Texture2D(IMG.Width, IMG.Height); texture.LoadImage(msFinger.ToArray()); array.SetPixels(texture.GetPixels(), i); } IMG.Dispose(); EditorUtility.ClearProgressBar(); array.Apply(); string newPath = path.Replace(".gif", ".asset"); AssetDatabase.CreateAsset(array, newPath); #endif #endif return(array); }
public String GetImg(String choix) { System.Drawing.Image img = null; if (choix.Contains("Hilton")) { img = System.Drawing.Image.FromFile(Server.MapPath("images") + @"\hilton.png"); } else if (choix.Contains("Mercure")) { img = System.Drawing.Image.FromFile(Server.MapPath("images") + @"\mercure.png"); } else if (choix.Contains("Ibis")) { img = System.Drawing.Image.FromFile(Server.MapPath("images") + @"\ibis.png"); } else if (choix.Contains("F1")) { img = System.Drawing.Image.FromFile(Server.MapPath("images") + @"\f1.png"); } System.IO.MemoryStream stream = new System.IO.MemoryStream(); img.Save(stream, System.Drawing.Imaging.ImageFormat.Png); Byte[] imgByte = stream.ToArray(); String imgStr = Convert.ToBase64String(imgByte); img.Dispose(); stream.Dispose(); return(imgStr); }
public static void GenerateHighThumbnail(string oldImagePath, string newImagePath, int width, int height) { System.Drawing.Image oldImage = System.Drawing.Image.FromFile(oldImagePath); int newWidth = AdjustSize(width, height, oldImage.Width, oldImage.Height).Width; int newHeight = AdjustSize(width, height, oldImage.Width, oldImage.Height).Height; //。。。。。。。。。。。 System.Drawing.Image thumbnailImage = oldImage.GetThumbnailImage(newWidth, newHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero); System.Drawing.Bitmap bm = new System.Drawing.Bitmap(thumbnailImage); //处理JPG质量的函数 System.Drawing.Imaging.ImageCodecInfo ici = GetEncoderInfo("image/jpeg,image/png"); if (ici != null) { System.Drawing.Imaging.EncoderParameters ep = new System.Drawing.Imaging.EncoderParameters(1); ep.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)100); bm.Save(newImagePath, ici, ep); //释放所有资源,不释放,可能会出错误。 ep.Dispose(); ep = null; } ici = null; bm.Dispose(); bm = null; thumbnailImage.Dispose(); thumbnailImage = null; oldImage.Dispose(); oldImage = null; }
/// <summary> /// 生成二维码方法一 /// </summary> private void CreateCode_Simple(string nr) { try { string imageUrl = string.Empty; QRCodeEncoder qrCodeEncoder = new QRCodeEncoder { QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE, QRCodeScale = nr.Length, QRCodeVersion = 0, QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M }; System.Drawing.Image image = qrCodeEncoder.Encode(nr, Encoding.UTF8); string filepath = Server.MapPath("~/") + UploadFileService.QRCodeImageFilePath; //如果文件夹不存在,则创建 if (!Directory.Exists(filepath)) { Directory.CreateDirectory(filepath); } string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + ".jpg"; imageUrl = filepath + filename; FileStream fs = new FileStream(imageUrl, FileMode.OpenOrCreate, FileAccess.Write); image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg); fs.Close(); image.Dispose(); this.QRCodeAttachUrl = UploadFileService.QRCodeImageFilePath + filename; } catch (Exception ex) { Alert.ShowInTop("操作有误,重新生成!", MessageBoxIcon.Warning); } }
static void Main() { // Create new PDF document Document pdfDocument = new Document(); pdfDocument.RegistrationName = "demo"; pdfDocument.RegistrationKey = "demo"; // Load image from file to System.Drawing.Image object (we need it to get the image resolution) System.Drawing.Image sysImage = System.Drawing.Image.FromFile(@".\scanned-invoice.png"); // Compute image size in PDF units (Points) float widthInPoints = sysImage.Width / sysImage.HorizontalResolution * 72f; float heightInPoints = sysImage.Height / sysImage.VerticalResolution * 72f; // Create page of computed size Page page = new Page(widthInPoints, heightInPoints); // Add page to the document pdfDocument.Pages.Add(page); Canvas canvas = page.Canvas; // Create Bytescout.PDF.Image object from loaded image Image pdfImage = new Image(sysImage); // Draw the image canvas.DrawImage(pdfImage, 0, 0, widthInPoints, heightInPoints); // Dispose the System.Drawing.Image object to free resources sysImage.Dispose(); // Create brush SolidBrush transparentBrush = new SolidBrush(new ColorGray(0)); // ... and make it transparent transparentBrush.Opacity = 0; // Draw text with transparent brush Font font16 = new Font(StandardFonts.Helvetica, 16); canvas.DrawString("Your Company Name", font16, transparentBrush, 40, 40); // Draw another text Font font10 = new Font(StandardFonts.Helvetica, 10); canvas.DrawString("Your Address", font10, transparentBrush, 40, 80); // Save document to file pdfDocument.Save("result.pdf"); // Cleanup pdfDocument.Dispose(); // Open result document in default associated application (for demo purpose) ProcessStartInfo processStartInfo = new ProcessStartInfo("result.pdf"); processStartInfo.UseShellExecute = true; Process.Start(processStartInfo); }
static void SetQuality(string file) { if (verbose_) { Output(file); } System.Drawing.Image imgInput = null; //System.IO.FileStream strmInput = System.IO.File.Open(file, System.IO.FileMode.Open); try { imgInput = System.Drawing.Image.FromFile(file); } catch (OutOfMemoryException) { } //strmInput.Close(); if (verbose_) { Output(imgInput.Width + "x" + imgInput.Height); } string newFile = file.Substring(0, file.LastIndexOf(".") + 1) + "new"; MiniSite.Util.SaveJpeg(imgInput, newFile, quality_); imgInput.Dispose(); System.IO.File.Delete(file); MiniSite.Util.MoveFile(newFile, file); }
public static void ResizeImage(string sourcefile, string destinationfile, int width, string ext, bool isThumb) { ImageFormat format = GetImageFormt(ext); var img = System.Drawing.Image.FromFile(sourcefile); if (img.Width >= width) { var w = width; var h = w * img.Height / img.Width; if (isThumb) { System.Drawing.Image thImg = img.GetThumbnailImage(w, h, null, IntPtr.Zero); thImg.Save(destinationfile, format); thImg.Dispose(); } else { System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(img, w, h); bitmap.Save(destinationfile, format); bitmap.Dispose(); } } else { System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(img, img.Width, img.Height); //bitmap.Clone(Rectangle.Round(new RectangleF(0,0,50,50)), PixelFormat.DontCare); bitmap.Save(destinationfile, format); bitmap.Dispose(); } }
/// <summary> /// 保存文件 返回对象 /// </summary> /// <param name="file"></param> /// <returns></returns> public UserPictureFile SavePostedFile(HttpPostedFile file) { byte[] btImgs = new byte[file.ContentLength]; file.InputStream.Read(btImgs, 0, btImgs.Length); ///压缩图片 System.Drawing.Image original_image = System.Drawing.Image.FromStream(file.InputStream); //使用流创建图片 int width = original_image.Width; //图片的宽度 int height = original_image.Height; //图片的高度 ComputWidthHeight(ref width, ref height); System.Drawing.Image newImg = PictureFileConverter.GetThumbnailImage("", width, height, file.InputStream); byte[] newBytes = PictureFileConverter.ImageToByteArray(newImg, System.Drawing.Imaging.ImageFormat.Jpeg); string fileBase64Str = Convert.ToBase64String(newBytes); newImg.Dispose(); //释放 file.InputStream.Dispose(); //释放 original_image.Dispose(); //释放 ///压缩图片 结束 UserPictureFile model = new UserPictureFile(); model.FileContent = fileBase64Str; model.Extension = file.ContentType; model.FileName = file.FileName; model.OperatorId = string.Empty; model.PictureFileNo = DateTime.Now.ToString("yyyyMMddHHmmssfff") + ThreadSafeRandom.Next(1000).ToString("000"); InsertPicFile(model); return(model); }
public static void Resize(string originalFile, string newFile, int newWidth, int maxHeight, bool onlyResizeIfWider) { System.Drawing.Image fullsizeImage = System.Drawing.Image.FromFile(originalFile); // Prevent using images internal thumbnail fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); fullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); if (onlyResizeIfWider && fullsizeImage.Width <= newWidth) { newWidth = fullsizeImage.Width; } int newHeight = fullsizeImage.Height * newWidth / fullsizeImage.Width; if (newHeight > maxHeight) { // Resize with height instead newWidth = fullsizeImage.Width * maxHeight / fullsizeImage.Height; newHeight = maxHeight; } System.Drawing.Image newImage = fullsizeImage.GetThumbnailImage(newWidth, newHeight, null, IntPtr.Zero); // Clear handle to original file so that we can overwrite it if necessary fullsizeImage.Dispose(); // Save resized picture newImage.Save(newFile); }
public string ToSmall(string originalImagePath) { bool isExist = WXSSK.Common.DirectoryAndFile.FileExists(originalImagePath); System.Drawing.Image imgOriginal = System.Drawing.Image.FromFile(Server.MapPath(originalImagePath)); //获取原图片的的宽度与高度 int originalWidth = imgOriginal.Width; int originalHeight = imgOriginal.Height; //originalHeight = (int)originalHeight * intWidth / originalWidth; //高度做相应比例缩小 //originalWidth = intWidth; //宽度等于缩略图片尺寸 System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(originalWidth, originalHeight); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap); //设置缩略图片质量 graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; graphics.DrawImage(imgOriginal, 0, 0, originalWidth, originalHeight); // 保存缩略图片 imgOriginal.Dispose(); WXSSK.Common.DirectoryAndFile.DeleteFile(originalImagePath); bitmap.Save(Server.MapPath(originalImagePath), System.Drawing.Imaging.ImageFormat.Jpeg); return(originalImagePath); }
/// <summary> /// Graba una imagen redimensionada y su thumbnail /// </summary> public void ConvertImage(string fileSource, string fileTarget, int intMaxImageWidth, int intThumbWidth) { System.Drawing.Image imageResized = null; // Graba el thumb de la imagen y la redimensiona si es necesario using (System.Drawing.Image image = FiltersHelpers.Load(fileSource)) { // Graba el thumb FiltersHelpers.SaveThumb(image, intThumbWidth, fileTarget); // Redimensiona la imagen (si es necesario) y la graba if (image.Width > intMaxImageWidth) { imageResized = FiltersHelpers.Resize(image, intMaxImageWidth); } // Libera la imagen image.Dispose(); } // Graba la imagen redimensionada if (imageResized != null) { FiltersHelpers.Save(imageResized, fileTarget); } else { LibCommonHelper.Files.HelperFiles.CopyFile(fileSource, fileTarget); } }
public static void Set(Uri uri, Style style) { Stream s = new System.Net.WebClient().OpenRead(uri.ToString()); System.Drawing.Image img = System.Drawing.Image.FromStream(s); string tempPath = Path.Combine(Path.GetTempPath(), "wallpaper.bmp"); img.Save(tempPath, System.Drawing.Imaging.ImageFormat.Bmp); RegistryKey key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true); if (style == Style.Stretched) { key.SetValue(@"WallpaperStyle", 2.ToString()); key.SetValue(@"TileWallpaper", 0.ToString()); } if (style == Style.Centered) { key.SetValue(@"WallpaperStyle", 1.ToString()); key.SetValue(@"TileWallpaper", 0.ToString()); } if (style == Style.Tiled) { key.SetValue(@"WallpaperStyle", 1.ToString()); key.SetValue(@"TileWallpaper", 1.ToString()); } SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, tempPath, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); img.Dispose(); }
private void Button_Click_1(object sender, RoutedEventArgs e) { Control ctl = (Control)sender; Window wndw = Window.GetWindow(ctl); RenderTargetBitmap bmp = new RenderTargetBitmap((int)TargetServiceGrid.ActualWidth, (int)TargetServiceGrid.ActualHeight, 96, 96, PixelFormats.Pbgra32); bmp.Clear(); bmp.Render(TargetServiceGrid); PngBitmapEncoder encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bmp)); MemoryStream fs = new MemoryStream(); encoder.Save(fs); System.Drawing.Image imgToCopy = System.Drawing.Image.FromStream(fs); System.Windows.Forms.Clipboard.SetImage(imgToCopy); imgToCopy.Dispose(); fs.Close(); fs.Dispose(); }
/// <summary> /// 生成二维码方法一 /// </summary> public static string CreateCode_Simple(string nr) { string imageUrl = string.Empty; if (!string.IsNullOrEmpty(nr)) { QRCodeEncoder qrCodeEncoder = new QRCodeEncoder { QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE, QRCodeScale = nr.Length, QRCodeVersion = 0, QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M }; System.Drawing.Image image = qrCodeEncoder.Encode(nr, Encoding.UTF8); string filepath = Funs.RootPath + UploadFileService.QRCodeImageFilePath; //如果文件夹不存在,则创建 if (!Directory.Exists(filepath)) { Directory.CreateDirectory(filepath); } string filename = DateTime.Now.ToString("yyyymmddhhmmssfff").ToString() + ".jpg"; FileStream fs = new FileStream(filepath + filename, FileMode.OpenOrCreate, FileAccess.Write); image.Save(fs, System.Drawing.Imaging.ImageFormat.Jpeg); fs.Close(); image.Dispose(); imageUrl = UploadFileService.QRCodeImageFilePath + filename; } return(imageUrl); }
public static void ResizeImage(Stream originalStream, Stream outStream, int newWidth, int maxHeight, bool onlyResizeIfWider, ImageFormat saveFormat) { System.Drawing.Image FullsizeImage = System.Drawing.Image.FromStream(originalStream); // Prevent using images internal thumbnail FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); if (onlyResizeIfWider) { if (FullsizeImage.Width <= newWidth) { newWidth = FullsizeImage.Width; } } int NewHeight = FullsizeImage.Height * newWidth / FullsizeImage.Width; if (NewHeight > maxHeight) { // Resize with height instead newWidth = FullsizeImage.Width * maxHeight / FullsizeImage.Height; NewHeight = maxHeight; } System.Drawing.Image NewImage = FullsizeImage.GetThumbnailImage(newWidth, NewHeight, null, IntPtr.Zero); // Clear handle to original file so that we can overwrite it if necessary FullsizeImage.Dispose(); // Save resized picture NewImage.Save(outStream, saveFormat); }
private bool isImageFile(string path) { bool result = false; System.Drawing.Image image = null; System.Drawing.Graphics graphics = null; try { image = System.Drawing.Image.FromFile(path); result = true; graphics = System.Drawing.Graphics.FromImage(image); } catch (System.Exception ex) { logException(ex); FileWriterWithAppendMode.GlobalWrite(path); } finally { if (graphics != null) { graphics.Dispose(); } if (image != null) { image.Dispose(); } } return(result); }
public void ResizeImage(string OrigFile, string NewFile, int NewWidth, int MaxHeight, bool ResizeIfWider) { System.Drawing.Image FullSizeImage = System.Drawing.Image.FromFile(OrigFile); // Ensure the generated thumbnail is not being used by rotating it 360 degrees FullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); FullSizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); if (ResizeIfWider) { if (FullSizeImage.Width <= NewWidth) { NewWidth = FullSizeImage.Width; } } int NewHeight = FullSizeImage.Height * NewWidth / FullSizeImage.Width; if (NewHeight > MaxHeight) // Height resize if necessary { NewWidth = FullSizeImage.Width * MaxHeight / FullSizeImage.Height; NewHeight = MaxHeight; } // Create the new image with the sizes we've calculated System.Drawing.Image NewImage = FullSizeImage.GetThumbnailImage(NewWidth, NewHeight, null, IntPtr.Zero); FullSizeImage.Dispose(); NewImage.Save(NewFile); }
public Image ResizeImage(Image origImg, int width, int maxHeight) { int newHeight = origImg.Height * width / origImg.Width; if (newHeight > maxHeight) { width = origImg.Width * maxHeight / origImg.Height; newHeight = maxHeight; } Image newImg = origImg.GetThumbnailImage(width, newHeight, null, IntPtr.Zero); origImg.Dispose(); return newImg; }