public JFIFThumbnail(byte[] palette, byte[] data) : this() { Format = ImageFormat.BMPPalette; Palette = palette; PixelData = data; }
public MemoryStream GenerateImage(Visual vsual, int widhth, int height, ImageFormat format) { BitmapEncoder encoder = null; switch (format) { case ImageFormat.JPG : encoder = new JpegBitmapEncoder(); break; case ImageFormat.PNG: encoder = new PngBitmapEncoder(); break; case ImageFormat.BMP: encoder = new BmpBitmapEncoder(); break; case ImageFormat.GIF: encoder = new GifBitmapEncoder(); break; case ImageFormat.TIF: encoder = new TiffBitmapEncoder(); break; } if (encoder == null) return null; RenderTargetBitmap rtb = this.RenderVisaulToBitmap(vsual, widhth, height); MemoryStream file = new MemoryStream(); encoder.Frames.Add(BitmapFrame.Create(rtb)); encoder.Save(file); return file; }
public static void TakeScreenShot(IWebDriver webDriver, string screenShotFileNameWithoutExtension, ImageFormat imageFormat, string screenShotDirectoryPath) { Screenshot screenShot = null; var browserName = string.Empty; if (webDriver.GetType() == typeof(InternetExplorerDriver)) { screenShot = ((InternetExplorerDriver)webDriver).GetScreenshot(); browserName = "IE"; } if (webDriver.GetType() == typeof(FirefoxDriver)) { screenShot = ((FirefoxDriver)webDriver).GetScreenshot(); browserName = "Firefox"; } if (webDriver.GetType() == typeof(ChromeDriver)) { screenShot = ((ChromeDriver)webDriver).GetScreenshot(); browserName = "Chrome"; } var screenShotFileName = screenShotFileNameWithoutExtension + "." + imageFormat.ToString().ToLower(); if (screenShot != null) { if (!string.IsNullOrEmpty(screenShotDirectoryPath)) { Directory.CreateDirectory(screenShotDirectoryPath).CreateSubdirectory(browserName); var browserScreenShotDirectoryPath = Path.Combine(screenShotDirectoryPath, browserName); Directory.CreateDirectory(browserScreenShotDirectoryPath); var screenShotFileFullPath = Path.Combine(browserScreenShotDirectoryPath, screenShotFileName); screenShot.SaveAsFile(screenShotFileFullPath, imageFormat); } } }
public ImageBuilder(int width, int height, ImageFormat format) { this.width = width; this.height = height; backend = handler.CreateImageBuilder (width, height, format); ctx = new Context (handler.CreateContext (backend)); }
public static void Save(this BitmapSource image, string filePath, ImageFormat format) { BitmapEncoder encoder = null; switch(format) { case ImageFormat.Png: encoder = new PngBitmapEncoder(); break; case ImageFormat.Jpeg: encoder = new JpegBitmapEncoder(); break; case ImageFormat.Bmp: encoder = new BmpBitmapEncoder(); break; } if (encoder == null) return; encoder.Frames.Add(BitmapFrame.Create(BitmapFrame.Create(image))); using (var stream = new FileStream(filePath, FileMode.Create)) encoder.Save(stream); }
private static void SaveFromMemory(PixelBuffer[] pixelBuffers, int count, ImageDescription description, Stream imageStream, ImageFormat imageFormat) { using (var bitmap = new Bitmap(description.Width, description.Height)) { var sourceArea = new Rectangle(0, 0, bitmap.Width, bitmap.Height); // Lock System.Drawing.Bitmap var bitmapData = bitmap.LockBits(sourceArea, ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppPArgb); try { // Copy memory if (description.Format == PixelFormat.R8G8B8A8_UNorm || description.Format == PixelFormat.R8G8B8A8_UNorm_SRgb) CopyMemoryBGRA(bitmapData.Scan0, pixelBuffers[0].DataPointer, pixelBuffers[0].BufferStride); else if (description.Format == PixelFormat.B8G8R8A8_UNorm || description.Format == PixelFormat.B8G8R8A8_UNorm_SRgb) Utilities.CopyMemory(bitmapData.Scan0, pixelBuffers[0].DataPointer, pixelBuffers[0].BufferStride); else throw new NotSupportedException(string.Format("Pixel format [{0}] is not supported", description.Format)); } finally { bitmap.UnlockBits(bitmapData); } // Save bitmap.Save(imageStream, imageFormat); } }
public override object CreateImageBuilder (int width, int height, ImageFormat format) { var flags = CGBitmapFlags.ByteOrderDefault; int bytesPerRow; switch (format) { case ImageFormat.ARGB32: bytesPerRow = width * 4; flags |= CGBitmapFlags.PremultipliedFirst; break; case ImageFormat.RGB24: bytesPerRow = width * 3; flags |= CGBitmapFlags.None; break; default: throw new NotImplementedException ("ImageFormat: " + format.ToString ()); } var bmp = new CGBitmapContext (IntPtr.Zero, width, height, 8, bytesPerRow, Util.DeviceRGBColorSpace, flags); bmp.TranslateCTM (0, height); bmp.ScaleCTM (1, -1); return new CGContextBackend { Context = bmp, Size = new CGSize (width, height), InverseViewTransform = bmp.GetCTM ().Invert () }; }
public static Image FromFile(string fileName, ImageFormat format) { using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) { return FromStream(stream, format); } }
private void GenerateImage( HttpResponse response, string textToInsert, int width, int height, Color backgroundColor, FontFamily fontFamily, float emSize, Brush brush, float x, float y, string contentType, ImageFormat imageFormat) { using (Bitmap bitmap = new Bitmap(width, height)) { using (Graphics graphics = Graphics.FromImage(bitmap)) { graphics.Clear(backgroundColor); graphics.DrawString(textToInsert, new Font(fontFamily, emSize), brush, x, y); response.ContentType = contentType; bitmap.Save(response.OutputStream, imageFormat); } } }
public void CropImageFile(string savePath, string sPhysicalPath, string sOrgFileName, string sThumbNailFileName, ImageFormat oFormat, int targetW, int targetH, int targetX, int targetY) { try { Size tsize = new Size(targetW, targetH); System.Drawing.Image oImg = System.Drawing.Image.FromFile(sPhysicalPath + @"\" + sOrgFileName); System.Drawing.Image oThumbNail = new Bitmap(tsize.Width, tsize.Height, oImg.PixelFormat); Graphics oGraphic = Graphics.FromImage(oThumbNail); oGraphic.CompositingQuality = CompositingQuality.HighQuality; oGraphic.SmoothingMode = SmoothingMode.HighQuality; oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic; oGraphic.DrawImage(oImg, new Rectangle(0, 0, targetW, targetH), targetX, targetY, targetW, targetH, GraphicsUnit.Pixel); oThumbNail.Save(savePath + @"\" + sThumbNailFileName, oFormat); oGraphic.Dispose(); oThumbNail.Dispose(); oImg.Dispose(); drag.Visible = false; ddFiles2.SelectedItem.Text = sThumbNailFileName; System.Drawing.Image origImg = System.Drawing.Image.FromFile(Server.MapPath("~/App_Uploads_Img/") + ddCat3.SelectedItem.Text + "/" + sThumbNailFileName); divimage.InnerHtml = "<img src=" + epicCMSLib.Navigation.SiteRoot + "App_Uploads_Img/" + ddCat3.SelectedItem.Text + "/" + ddFiles2.SelectedItem.Text + "></img>"; Label8.Text = "Your selected Image's Width is " + origImg.Width.ToString() + "px and Height is " + origImg.Height.ToString() + "px."; Hidden1.Value = origImg.Width.ToString(); Hidden2.Value = origImg.Height.ToString(); UpdatePanel3.Update(); lbSuccess3.ForeColor = System.Drawing.Color.Green; lbSuccess3.Text = "Image " + sThumbNailFileName + " created."; } catch (Exception e1) { errorlabelcrop.ForeColor = System.Drawing.Color.Red; errorlabelcrop.Text = e1.Message; } }
/// <summary> /// /// </summary> /// <param name="index"></param> /// <param name="outputFileName"></param> /// <param name="outputformat"></param> public void ChartToImage(int index, string outputFileName, ImageFormat outputformat) { try { //check whether file is set or not if (FileName == "") throw new Exception("No file name specified"); else if (WorksheetName == "") throw new Exception("No Worksheet name specified"); //build URI string strURI = Aspose.Cloud.Common.Product.BaseProductUri + "/cells/" + FileName; strURI += "/worksheets/" + WorksheetName + "/charts/" + index + "?format=" + outputformat; //sign URI string signedURI = Utils.Sign(strURI); //get response stream Stream responseStream = Utils.ProcessCommand(signedURI, "GET"); using (Stream fileStream = System.IO.File.OpenWrite(outputFileName)) { Utils.CopyStream(responseStream, fileStream); } responseStream.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } }
/// <summary> /// Converts a dot file to the requested image format /// </summary> /// <param name="dotFilePath">The path to the dot file to convert</param> /// <param name="outputFilePath">The file path of where to save the image</param> /// <param name="imageFormat">The image format to use when converitng the dot file</param> /// <returns>A task representing the asynchronous operation</returns> public Task ConvertAsync(string dotFilePath, string outputFilePath, ImageFormat imageFormat) { if (!File.Exists(dotFilePath)) { throw new ArgumentException("The supplied dot file does not exist", "dotFilePath"); } return Task.Run(() => { const int sixtySeconds = 60 * 1000; var outputFormat = Enum.GetName(typeof(ImageFormat), (int)imageFormat).ToLower(); var process = new Process { StartInfo = new ProcessStartInfo { Arguments = string.Format(@"-T{0} -o ""{1}"" ""{2}""", outputFormat, outputFilePath, dotFilePath), CreateNoWindow = true, FileName = Path.Combine(_GraphVizBinPath, "dot.exe"), UseShellExecute = false } }; process.Start(); process.WaitForExit(sixtySeconds); }); }
public void AddWatermark(string filename, ImageFormat imageFormat, Stream outputStream, HttpContext ctx) { Image bitmap = Image.FromFile(filename); Font font = new Font("Arial", 13, FontStyle.Bold, GraphicsUnit.Pixel); Random rnd = new Random(); Color color = Color.FromArgb(200, rnd.Next(255), rnd.Next(255), rnd.Next(255)); //Adds a black watermark with a low alpha value (almost transparent). Point atPoint = new Point(bitmap.Width / 2 - 40, bitmap.Height / 2 - 7); //The pixel point to draw the watermark at (this example puts it at 100, 100 (x, y)). SolidBrush brush = new SolidBrush(color); string watermarkText = "voobrazi.by"; Graphics graphics; try { graphics = Graphics.FromImage(bitmap); } catch { Image temp = bitmap; bitmap = new Bitmap(bitmap.Width, bitmap.Height); graphics = Graphics.FromImage(bitmap); graphics.DrawImage(temp, new Rectangle(0, 0, bitmap.Width, bitmap.Height), 0, 0, bitmap.Width, bitmap.Height, GraphicsUnit.Pixel); temp.Dispose(); } graphics.DrawString(watermarkText, font, brush, atPoint); graphics.Dispose(); bitmap.Save(outputStream, imageFormat); bitmap.Dispose(); }
public static ImageCodecInfo GetImageEncoder(ImageFormat format) { return ImageCodecInfo.GetImageEncoders().ToList().Find(delegate(ImageCodecInfo codec) { return codec.FormatID == format.Guid; }); }
public override object CreateImageBuilder (int width, int height, ImageFormat format) { return new ImageBuilder () { Width = width, Height = height }; }
public ImageBuilder(int width, int height, ImageFormat format) { handler = ToolkitEngine.ImageBuilderBackendHandler; this.width = width; this.height = height; backend = handler.CreateImageBuilder (width, height, format); ctx = new Context (handler.CreateContext (backend), ToolkitEngine); }
public static async Task<IControl> LoadAsync(this ImageSource source, CancellationToken cancellationToken = default(CancellationToken), ImageFormat format = ImageFormat.Unknown) { if (source == null) return null; var handler = Registrar.Registered.GetHandler<IImageSourceHandler>(source.GetType()); return await handler.GetImageAsync(source, format, cancellationToken); }
/// <summary> /// Constructor /// </summary> /// <param name="imageFormat">Image Format to save images as</param> public Recorder(ImageFormat imageFormat = null) { if (imageFormat == null) return; this.imageFormat = imageFormat; this.imageExtension = "." + imageFormat.ToString().ToLower(); }
private string GetExtension(ImageFormat imageFormat) { if (imageFormat == ImageFormat.Png) return "png"; else if (imageFormat == ImageFormat.Jpeg) return "jpg"; else throw new ArgumentOutOfRangeException("imageFormat"); }
public async Task<IControl> GetImage(UriImageSource source, ImageFormat format) { using (var stream = await Forms.UpdateContext.Wait(source.GetStreamAsync())) { if (stream == null) throw new ArgumentException("Resource not found", "source"); return await ImageFactory.CreateFromStream(stream, format, CancellationToken.None); } }
private static OpenTK.Graphics.OpenGL4.PixelFormat FromPfimFormat(ImageFormat f) { if (f == ImageFormat.Rgb24) return OpenTK.Graphics.OpenGL4.PixelFormat.Bgr; else if (f == ImageFormat.Rgba32) return OpenTK.Graphics.OpenGL4.PixelFormat.Bgra; throw new Exception("Unknown Image format"); }
public override object CreateImageBuilder (int width, int height, ImageFormat format) { Cairo.Format cformat; switch (format) { case ImageFormat.ARGB32: cformat = Cairo.Format.ARGB32; break; default: cformat = Cairo.Format.RGB24; break; } return new Cairo.ImageSurface (cformat, width, height); }
//// [TestCase("test.jpg", ImageFormat.Jpeg)] public void GetFormat_TestFiles_(string fileName, ImageFormat expectedImageFormat) { var image = new OxyImage(File.ReadAllBytes(@"Imaging\TestImages\" + fileName)); Assert.AreEqual(expectedImageFormat, image.Format); Assert.AreEqual(137, image.Width); Assert.AreEqual(59, image.Height); Assert.AreEqual(72, Math.Round(image.DpiX)); Assert.AreEqual(72, Math.Round(image.DpiY)); }
public static Image FromStream(Stream stream, ImageFormat format) { switch (format) { case ImageFormat.Tga: return Tga.FromStream(stream); } throw new NotImplementedException("ImageFormat." + format.ToString() + " not implemented."); }
public KnownImage(string path, Size size, ImageFormat imageFormat = ImageFormat.Jpeg) { Path = path; Size = size; ImageFormat = imageFormat; var regex = new Regex(@"(?<name>\w+)\.\w+?$", RegexOptions.IgnoreCase); var matches = regex.Matches(Path); Name = matches[0].Groups["name"].Value; }
static ImageFormat() { _bmp = new ImageFormat("BMP"); _gif = new ImageFormat("GIF"); _icon = new ImageFormat("ICON"); _jpeg = new ImageFormat("JPEG"); _png = new ImageFormat("PNG"); _tiff = new ImageFormat("TIFF"); _wmf = new ImageFormat("WMF"); _emf = new ImageFormat("EMF"); }
public async Task<IControl> GetImage(FileImageSource source, ImageFormat format) { var path = Path.Combine(Forms.Game.Content.RootDirectory, source.File); if (File.Exists(path)) { using (var stream = File.OpenRead(path)) return await ImageFactory.CreateFromStream(stream, format, CancellationToken.None); } var texture = Forms.Game.Content.Load<Texture2D>(source.File); return ImageFactory.CreateFromTexture(texture, format); }
/// <summary> /// Gets the full path to the image asset, suitable for current screen resolution /// </summary> /// <param name="path">Path to image asset, relative to app root</param> /// <returns></returns> public static Uri GetUri(string path, ImageFormat imageFormat = ImageFormat.JPG) { switch (ResolutionHelper.CurrentResolution) { case Resolutions.HD: return new Uri("{0}.Screen-720p.{1}".FormatWith(path, imageFormat.ToString().ToLowerInvariant()), UriKind.Relative); case Resolutions.WXGA: return new Uri("{0}.Screen-WXGA.{1}".FormatWith(path, imageFormat.ToString().ToLowerInvariant()), UriKind.Relative); case Resolutions.WVGA: return new Uri("{0}.Screen-WVGA.{1}".FormatWith(path, imageFormat.ToString().ToLowerInvariant()), UriKind.Relative); default: throw new InvalidOperationException("Unknown resolution type"); } }
public Task<IControl> GetImageAsync(ImageSource imageSource, ImageFormat format, CancellationToken cancellationToken) { var fileSource = (FileImageSource)imageSource; string asset = fileSource.File; if (format == ImageFormat.Unknown) format = ImageFactory.DetectFormat(asset); string cacheKey = format.ToString() + "|" + asset; return _cachedImages.GetOrAdd(cacheKey, k => GetImage(fileSource, format)); }
public KnownImage(string path, Size size, ImageFormat imageFormat = ImageFormat.Jpeg) { Path = path; Size = size; ImageFormat = imageFormat; var regex = new Regex(@"(?<name>\w+)\.\w+?$", RegexOptions.IgnoreCase); var matches = regex.Matches(Path); Name = matches[0].Groups["name"].Value; m_fileTask = Package.Current.InstalledLocation.GetFileAsync(Path).AsTask(); m_bufferTask = m_fileTask.ContinueWith(fileTask => FileIO.ReadBufferAsync(fileTask.Result).AsTask(), TaskContinuationOptions.OnlyOnRanToCompletion).Unwrap(); }
/// <summary> /// Constructor. /// </summary> public ImageResizer() { MaxX = MaxY = 200; TrimImage = false; SaveFormat = ImageFormat.Jpeg; }
public Image(Resource resource, string filename, int curImage, int nFaces, int nMipmaps, ImageFormat format) { Filename = filename; Format = format; // load relevant information Layers = new List <Face>(nFaces); for (var curLayer = 0; curLayer < nFaces; ++curLayer) { Layers.Add(new Face(resource, curImage, curLayer, nMipmaps)); } }
public static void ConvertToHtml(string file, string outputDirectory) { var fi = new FileInfo(file); byte[] byteArray = File.ReadAllBytes(fi.FullName); using (MemoryStream memoryStream = new MemoryStream()) { memoryStream.Write(byteArray, 0, byteArray.Length); using (WordprocessingDocument wDoc = WordprocessingDocument.Open(memoryStream, true)) { var destFileName = new FileInfo(fi.Name.Replace(".docx", ".html")); if (outputDirectory != null && outputDirectory != string.Empty) { DirectoryInfo di = new DirectoryInfo(outputDirectory); if (!di.Exists) { throw new OpenXmlPowerToolsException("Output directory does not exist"); } destFileName = new FileInfo(Path.Combine(di.FullName, destFileName.Name)); } var imageDirectoryName = destFileName.FullName.Substring(0, destFileName.FullName.Length - 5) + "_files"; int imageCounter = 0; var pageTitle = (string)wDoc.CoreFilePropertiesPart.GetXDocument().Descendants(DC.title).FirstOrDefault(); if (pageTitle == null) { pageTitle = fi.FullName; } HtmlConverterSettings settings = new HtmlConverterSettings() { PageTitle = pageTitle, FabricateCssClasses = true, CssClassPrefix = "pt-", RestrictToSupportedLanguages = false, RestrictToSupportedNumberingFormats = false, ImageHandler = imageInfo => { DirectoryInfo localDirInfo = new DirectoryInfo(imageDirectoryName); if (!localDirInfo.Exists) { localDirInfo.Create(); } ++imageCounter; string extension = imageInfo.ContentType.Split('/')[1].ToLower(); ImageFormat imageFormat = null; if (extension == "png") { // Convert png to jpeg. extension = "gif"; imageFormat = ImageFormat.Gif; } else if (extension == "gif") { imageFormat = ImageFormat.Gif; } else if (extension == "bmp") { imageFormat = ImageFormat.Bmp; } else if (extension == "jpeg") { imageFormat = ImageFormat.Jpeg; } else if (extension == "tiff") { // Convert tiff to gif. extension = "gif"; imageFormat = ImageFormat.Gif; } else if (extension == "x-wmf") { extension = "wmf"; imageFormat = ImageFormat.Wmf; } // If the image format isn't one that we expect, ignore it, // and don't return markup for the link. if (imageFormat == null) { return(null); } string imageFileName = imageDirectoryName + "/image" + imageCounter.ToString() + "." + extension; try { imageInfo.Bitmap.Save(imageFileName, imageFormat); } catch (System.Runtime.InteropServices.ExternalException) { return(null); } XElement img = new XElement(Xhtml.img, new XAttribute(NoNamespace.src, imageFileName), imageInfo.ImgStyleAttribute, imageInfo.AltText != null ? new XAttribute(NoNamespace.alt, imageInfo.AltText) : null); return(img); } }; XElement html = HtmlConverter.ConvertToHtml(wDoc, settings); // Note: the xhtml returned by ConvertToHtmlTransform contains objects of type // XEntity. PtOpenXmlUtil.cs define the XEntity class. See // http://blogs.msdn.com/ericwhite/archive/2010/01/21/writing-entity-references-using-linq-to-xml.aspx // for detailed explanation. // // If you further transform the XML tree returned by ConvertToHtmlTransform, you // must do it correctly, or entities will not be serialized properly. var htmlString = html.ToString(SaveOptions.DisableFormatting); File.WriteAllText(destFileName.FullName, htmlString, Encoding.UTF8); } } }
/// <summary> /// Creates an instance of this class /// </summary> /// <param name="tileSource">The tile source</param> /// <param name="layerName">The layers name</param> /// <param name="transparentColor">The color that should be treated as <see cref="Color.Transparent"/></param> /// <param name="showErrorInTile">Value indicating that an error tile should be generated for non-existent tiles</param> /// <param name="fileCache">If the layer should use a file-cache so store tiles, set this to a fileCacheProvider. Set to null to avoid filecache</param> /// <param name="imgFormat">Set the format of the tiles to be used</param> public TileAsyncLayer(ITileSource tileSource, string layerName, Color transparentColor, bool showErrorInTile, FileCache fileCache, ImageFormat imgFormat) : base(tileSource, layerName, transparentColor, showErrorInTile, fileCache, imgFormat) { SetTileSource(tileSource); }
private static async Task CreateFromB64Async(string sourceBase64, IImageUrls urls, ImageFormat toFormat) { var cf = new UserImageLoader(); await cf.CreateFromB64Async(sourceBase64, urls, toFormat); }
/// <summary> /// 将图片转为base64字符串 /// 使用指定格式,并添加data:image/jpg;base64,前缀 /// </summary> /// <param name="img">图片对象</param> /// <param name="imageFormat">指定格式</param> /// <returns></returns> public static string ToBase64StringUrl(Image img, ImageFormat imageFormat) { string base64 = ToBase64String(img, imageFormat); return($"data:image/{imageFormat.ToString().ToLower()};base64,{base64}"); }
public void SaveImage(Texture2D image, string name, ImageFormat format = ImageFormat.JPG, Action <string> callback = null) { Debug.LogWarning(UnsupportedMessage); }
internal void WriteTo(Stream stream, ImageFormat format) { throw new NotImplementedException("PCL"); }
/// <summary> /// 获取图片的类型 /// </summary> /// <param name="extention">文件后缀</param> /// <returns>图片类型</returns> private ImageFormat GetImageFormat(string extention) { ImageFormat format = ImageFormat.Bmp; switch (extention) { case ".jpg": { format = ImageFormat.Jpeg; break; } case ".jpeg": { format = ImageFormat.Jpeg; break; } case ".bmp": { format = ImageFormat.Bmp; break; } case ".emf": { format = ImageFormat.Emf; break; } case ".exif": { format = ImageFormat.Exif; break; } case ".gif": { format = ImageFormat.Gif; break; } case ".ico": { format = ImageFormat.Icon; break; } case ".icon": { format = ImageFormat.Icon; break; } case ".png": { format = ImageFormat.Png; break; } case ".tiff": { format = ImageFormat.Tiff; break; } case ".wmf": { format = ImageFormat.Wmf; break; } } return(format); }
ImageCodecInfo GetEncoder(ImageFormat format) { ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders(); return(codecs.FirstOrDefault(codec => codec.FormatID == format.Guid)); }
public static MemoryStream AddWatermark(Image originImage, string imgExtensionName, Image watermarkImg, WatermarkPositionEnum watermarkPosition = WatermarkPositionEnum.RightButtom, int textPadding = 10) { if (originImage == null) { return(null); } using (var graphic = Graphics.FromImage(originImage)) { if (watermarkImg != null) { var width = (int)(originImage.Width * 0.3); var height = (int)(originImage.Height * 0.3); watermarkImg = ZoomImage(watermarkImg, width, height); int x = textPadding, y = textPadding; switch (watermarkPosition) { case WatermarkPositionEnum.LeftTop: x = textPadding; y = textPadding; break; case WatermarkPositionEnum.LeftCenter: x = textPadding; y = (int)((originImage.Height / 2.0) - watermarkImg.Height - textPadding); break; case WatermarkPositionEnum.LeftButtom: x = textPadding; y = originImage.Height - (int)watermarkImg.Height - textPadding; break; case WatermarkPositionEnum.CenterTop: x = (int)((originImage.Width / 2) - watermarkImg.Width - textPadding); y = textPadding; break; case WatermarkPositionEnum.Center: x = (int)((originImage.Width / 2) - watermarkImg.Width - textPadding); y = originImage.Height - (int)watermarkImg.Height - textPadding; break; case WatermarkPositionEnum.CenterButtom: x = (int)((originImage.Width / 2) - watermarkImg.Width - textPadding); y = originImage.Height - (int)watermarkImg.Height - textPadding; break; case WatermarkPositionEnum.RightTop: x = originImage.Width - (int)watermarkImg.Width - textPadding; y = textPadding; break; case WatermarkPositionEnum.RightCenter: x = originImage.Width - (int)watermarkImg.Width - textPadding; y = (int)((originImage.Height / 2.0) - watermarkImg.Height - textPadding); break; case WatermarkPositionEnum.RightButtom: x = originImage.Width - (int)watermarkImg.Width - textPadding; y = originImage.Height - (int)watermarkImg.Height - textPadding; break; default: x = textPadding; y = textPadding; break; } graphic.DrawImage(watermarkImg, new Point(x, y)); } ImageFormat fmt = null; switch (imgExtensionName) { case ".png": fmt = ImageFormat.Png; break; case ".jpg": case ".jpeg": fmt = ImageFormat.Jpeg; break; case ".bmp": fmt = ImageFormat.Bmp; break; } var watermarkedStream = new MemoryStream(); originImage.Save(watermarkedStream, fmt); return(watermarkedStream); } }
/// <summary> /// 无损压缩图片 /// </summary> /// <param name="sFile">原图片</param> /// <param name="dFile">压缩后保存位置</param> /// <param name="height">高度</param> /// <param name="width"></param> /// <param name="flag">压缩质量 1-100</param> /// <param name="type">压缩缩放类型</param> /// <returns></returns> public bool Compress(string sFile, string dFile, int height, int width, int flag, ImageCompressType type) { System.Drawing.Image iSource = System.Drawing.Image.FromFile(sFile); ImageFormat tFormat = iSource.RawFormat; //****缩放后的宽度和高度 int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = iSource.Width; int oh = iSource.Height; switch (type) { case ImageCompressType.N: //***原始高宽 { towidth = ow; toheight = oh; break; } case ImageCompressType.WH: //指定高宽缩放(可能变形) { break; } case ImageCompressType.W: //指定宽,高按比例 { toheight = iSource.Height * width / iSource.Width; break; } case ImageCompressType.H: //指定高,宽按比例 { towidth = iSource.Width * height / iSource.Height; break; } case ImageCompressType.Cut: //指定高宽裁减(不变形) { if ((double)iSource.Width / (double)iSource.Height > (double)towidth / (double)toheight) { oh = iSource.Height; ow = iSource.Height * towidth / toheight; y = 0; x = (iSource.Width - ow) / 2; } else { ow = iSource.Width; oh = iSource.Width * height / towidth; x = 0; y = (iSource.Height - oh) / 2; } break; } default: break; } Bitmap ob = new Bitmap(towidth, toheight); Graphics g = Graphics.FromImage(ob); g.Clear(System.Drawing.Color.WhiteSmoke); g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(iSource , new Rectangle(x, y, towidth, toheight) , new Rectangle(0, 0, iSource.Width, iSource.Height) , GraphicsUnit.Pixel); g.Dispose(); //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int i = 0; i < arrayICI.Length; i++) { if (arrayICI[i].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[i]; break; } } if (jpegICIinfo != null) { ob.Save(dFile, jpegICIinfo, ep);//dFile是压缩后的新路径 } else { ob.Save(dFile, tFormat); } return(true); } catch { return(false); } finally { iSource.Dispose(); ob.Dispose(); } }
public static byte[] ToByteArray(this Image image, ImageFormat format) { using var stream = new MemoryStream(); image.Save(stream, format); return(stream.ToArray()); }
/// <summary> /// Initialize<br/> /// 初始化<br/> /// </summary> /// <param name="image">Image object</param> /// <param name="format">Image format, default is Jpeg</param> public ImageResult(Image image, ImageFormat format = null) { Image = image; Format = format ?? ImageFormat.Jpeg; }
public static void AttachText(string text, string file) { if (!string.IsNullOrEmpty(text) && File.Exists(file)) { var oFile = new FileInfo(file); string strTempFile = Path.Combine(oFile.DirectoryName, Guid.NewGuid() + oFile.Extension); oFile.CopyTo(strTempFile); Image img = Image.FromFile(strTempFile); ImageFormat thisFormat = img.RawFormat; int nHeight = img.Height; int nWidth = img.Width; var outBmp = new Bitmap(nWidth, nHeight); Graphics g = Graphics.FromImage(outBmp); g.Clear(Color.White); g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.DrawImage(img, new Rectangle(0, 0, nWidth, nHeight), 0, 0, nWidth, nHeight, GraphicsUnit.Pixel); var sizes = new[] { 0x10, 14, 12, 10, 8, 6, 4 }; Font crFont = null; var crSize = new SizeF(); for (int i = 0; i < 7; i++) { crFont = new Font("arial", sizes[i], FontStyle.Bold); crSize = g.MeasureString(text, crFont); if (((ushort)crSize.Width) < ((ushort)nWidth)) { break; } } var yPixlesFromBottom = (int)(nHeight * 0.08); float yPosFromBottom = (nHeight - yPixlesFromBottom) - (crSize.Height / 2f); float xCenterOfImg = nWidth / 2; var strFormat = new StringFormat(); strFormat.Alignment = StringAlignment.Center; var semiTransBrush2 = new SolidBrush(Color.FromArgb(0x99, 0, 0, 0)); g.DrawString(text, crFont, semiTransBrush2, new PointF(xCenterOfImg + 1f, yPosFromBottom + 1f), strFormat); var semiTransBrush = new SolidBrush(Color.FromArgb(0x99, 0xff, 0xff, 0xff)); g.DrawString(text, crFont, semiTransBrush, new PointF(xCenterOfImg, yPosFromBottom), strFormat); g.Dispose(); var encoderParams = new EncoderParameters(); var quality = new[] { 100L }; var encoderParam = new EncoderParameter(Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegIci = arrayIci.FirstOrDefault(t => t.FormatDescription.Equals("JPEG")); if (jpegIci != null) { try { oFile.Delete(); outBmp.Save(file, jpegIci, encoderParams); } catch (Exception oE) { string str = oE.Message; } } else { outBmp.Save(file, thisFormat); } img.Dispose(); outBmp.Dispose(); File.Delete(strTempFile); } }
private static ImageCodecInfo GetEncoderInfo(ImageFormat imgFmt) => ImageCodecInfo.GetImageDecoders().First(c => c.FormatID == imgFmt.Guid);
private static void SaveAsImage(IPrintable document, string path, ImageFormat format, bool selectedOnly, bool transparent) { const int Margin = 20; RectangleF areaF = document.GetPrintingArea(selectedOnly); areaF.Offset(0.5F, 0.5F); Rectangle area = Rectangle.FromLTRB((int)areaF.Left, (int)areaF.Top, (int)Math.Ceiling(areaF.Right), (int)Math.Ceiling(areaF.Bottom)); if (format == ImageFormat.Emf) // Save to metafile { Graphics metaG = _control.CreateGraphics(); IntPtr hc = metaG.GetHdc(); Graphics g = null; try { // Set drawing parameters Metafile meta = new Metafile(path, hc); g = Graphics.FromImage(meta); g.SmoothingMode = SmoothingMode.HighQuality; if (DiagramEditor.Settings.Default.UseClearTypeForImages) { g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; } else { g.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; } g.TranslateTransform(-area.Left, -area.Top); // Draw image IGraphics graphics = new GdiGraphics(g); document.Print(graphics, selectedOnly, Style.CurrentStyle); meta.Dispose(); } catch (Exception ex) { MessageBox.Show( string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage, Strings.ErrorsReason, ex.Message), Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { metaG.ReleaseHdc(); metaG.Dispose(); g?.Dispose(); } } else // Save to rastered image { int width = area.Width + Margin * 2; int height = area.Height + Margin * 2; PixelFormat pixelFormat; if (transparent) { pixelFormat = PixelFormat.Format32bppArgb; } else { pixelFormat = PixelFormat.Format24bppRgb; } using (Bitmap image = new Bitmap(width, height, pixelFormat)) using (Graphics g = Graphics.FromImage(image)) { // Set drawing parameters g.SmoothingMode = SmoothingMode.HighQuality; if (DiagramEditor.Settings.Default.UseClearTypeForImages && !transparent) { g.TextRenderingHint = TextRenderingHint.ClearTypeGridFit; } else { g.TextRenderingHint = TextRenderingHint.SingleBitPerPixelGridFit; } g.TranslateTransform(Margin - area.Left, Margin - area.Top); // Draw image if (!transparent) { g.Clear(Style.CurrentStyle.BackgroundColor); } IGraphics graphics = new GdiGraphics(g); document.Print(graphics, selectedOnly, Style.CurrentStyle); try { image.Save(path, format); } catch (Exception ex) { MessageBox.Show( string.Format("{0}\n{1}: {2}", Strings.ErrorInSavingImage, Strings.ErrorsReason, ex.Message), Strings.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
/// <summary>Initialize the load info structure</summary> public DdsLoadInfo(bool isCompresed, bool isSwap, bool isPalette, uint aDivSize, uint aBlockBytes, int aDepth, ImageFormat format) { Format = format; Compressed = isCompresed; Swap = isSwap; Palette = isPalette; DivSize = aDivSize; BlockBytes = aBlockBytes; Depth = aDepth; }
public void RenderPortion(Point portionOffset, Size portionSize, int itemsPerPage, int pageNumber, ImageFormat format, Stream output) { using (Bitmap bitmap = new Bitmap(portionSize.Width, portionSize.Height)) { using (Graphics graphics = Graphics.FromImage(bitmap)) { float x = portionSize.Width * portionOffset.X; float y; if (portionOffset.Y < 0) // Render head { y = 0; } else { y = portionSize.Height * portionOffset.Y + pageNumber * _itemHeight * itemsPerPage + _head.CalculateHeight(_headerItemHeight); } using (Matrix matrix = new Matrix()) { matrix.Translate(-x, -y); graphics.Transform = matrix; } DrawingContext context = new DrawingContext(_startDate, x, y, portionSize.Width, portionSize.Height, itemsPerPage, pageNumber); context.Graphics = graphics; context.Provider = _provider; context.HeaderItemHeight = _headerItemHeight; context.ItemHeight = _itemHeight; _data.Render(context); } bitmap.Save(output, format); } }
/// <summary> /// Captures a screen shot of the entire desktop, and saves it to a file /// </summary> /// <param name="filename"></param> /// <param name="format"></param> public void CaptureScreenToFile(string filename, ImageFormat format) { Image img = CaptureScreen(); img.Save(filename, format); }
public void SetupCamera() { if (Camera != null) { return; } ZXing.Net.Mobile.Android.PermissionsHandler.CheckCameraPermissions(_context); var perf = PerformanceCounter.Start(); OpenCamera(); PerformanceCounter.Stop(perf, "Setup Camera took {0}ms"); if (Camera == null) { return; } perf = PerformanceCounter.Start(); ApplyCameraSettings(); try { Camera.SetPreviewDisplay(_holder); var previewParameters = Camera.GetParameters(); var previewSize = previewParameters.PreviewSize; var bitsPerPixel = ImageFormat.GetBitsPerPixel(previewParameters.PreviewFormat); int bufferSize = (previewSize.Width * previewSize.Height * bitsPerPixel) / 8; const int NUM_PREVIEW_BUFFERS = 5; for (uint i = 0; i < NUM_PREVIEW_BUFFERS; ++i) { using (var buffer = new FastJavaByteArray(bufferSize)) Camera.AddCallbackBuffer(buffer); } Camera.StartPreview(); Camera.SetNonMarshalingPreviewCallback(_cameraEventListener); } catch (Exception ex) { Android.Util.Log.Debug(MobileBarcodeScanner.TAG, ex.ToString()); return; } finally { PerformanceCounter.Stop(perf, "Setup Camera Parameters took {0}ms"); } // Docs suggest if Auto or Macro modes, we should invoke AutoFocus at least once var currentFocusMode = Camera.GetParameters().FocusMode; if (currentFocusMode == Camera.Parameters.FocusModeAuto || currentFocusMode == Camera.Parameters.FocusModeMacro) { AutoFocus(); } }
/// <summary> /// Captures a screen shot of a specific window, and saves it to a file /// </summary> /// <param name="handle"></param> /// <param name="filename"></param> /// <param name="format"></param> public void CaptureWindowToFile(IntPtr handle, string filename, ImageFormat format) { Image img = CaptureWindow(handle); img.Save(filename, format); }
public void IsDirectPrintingSupported_ImageFormatNotSupported_ReturnsExpected(ImageFormat imageFormat) { var printerSettings = new PrinterSettings(); Assert.False(printerSettings.IsDirectPrintingSupported(imageFormat)); }
public IActionResult DodajIzmijeni(DodajIzmijeniReceptViewModel model) { var slikaUrl = model.SlikaURL; var korisnikId = int.Parse(User.FindFirst(x => x.Type == "Id")?.Value); Recept recept = null; if (model.ReceptId != 0) { recept = _receptRepo.Get(model.ReceptId); } if (recept != null && recept.KorisnikId != korisnikId) { return(View(model)); } if (string.IsNullOrEmpty(slikaUrl)) { if (model.Slika == null) { ModelState.AddModelError("Slika", "Molimo da odaberete sliku"); return(View(model)); } if (model.Slika.Length > MAX_UPLOAD_SIZE * 1024 * 1024) { ModelState.AddModelError("Slika", $"Maksimalna veličina slike ne smije biti veća od {MAX_UPLOAD_SIZE}MB"); return(View(model)); } if (ImageFormat.GetImageFormat(model.Slika) == null) { ModelState.AddModelError("Slika", "Podržane ekstenzije fajla su: .bmp, .png, .tiff, .tiff2, .jpg, .jpeg"); return(View(model)); } slikaUrl = FileHelpers.GetUniqueFileName(model.Slika.FileName); var uploadFolder = Path.Combine(_hostingEnvironment.WebRootPath, "slike-recepata"); var filePath = Path.Combine(uploadFolder, slikaUrl); if (!Directory.Exists(uploadFolder)) { Directory.CreateDirectory(uploadFolder); } if (recept != null) { System.IO.File.Delete(Path.Combine(uploadFolder, recept.SlikaURL)); } using (var stream = new FileStream(filePath, FileMode.Create)) { model.Slika.CopyTo(stream); } } _receptRepo.Update(new Recept() { ReceptId = model.ReceptId, DatumObjave = recept == null ? DateTime.Now : recept.DatumObjave, Kategorija = model.Kategorija, KorisnikId = korisnikId, Naziv = model.Naziv, Priprema = _htmlSanitizer.Sanitize(model.Priprema), Privatan = model.Privatan, Sastav = model.Sastav, SlikaURL = slikaUrl }); _receptRepo.SaveChanges(); TempData["poruka"] = "Recept uspješno sačuvan."; return(RedirectToAction("Index", "Home")); }
public void IsDirectPrintingSupported_ImageFormatSupported_ReturnsExpected(ImageFormat imageFormat) { var printerSettings = new PrinterSettings(); bool supported = printerSettings.IsDirectPrintingSupported(imageFormat); }
public static MemoryStream AddWatermark(Image originImage, string imgExtensionName, string watermarkText, Color color, WatermarkPositionEnum watermarkPosition = WatermarkPositionEnum.RightButtom, int textPadding = 10, int fontSize = 20, Font font = null) { if (originImage == null) { return(null); } using (var graphic = Graphics.FromImage(originImage)) { if (!string.IsNullOrEmpty(watermarkText)) { var brush = new SolidBrush(color); if (fontSize < 5) { fontSize = 5; } var f = font ?? new Font(FontFamily.GenericSansSerif, fontSize, FontStyle.Bold, GraphicsUnit.Pixel); var textSize = graphic.MeasureString(watermarkText, f); int x = textPadding, y = textPadding; switch (watermarkPosition) { case WatermarkPositionEnum.LeftTop: x = textPadding; y = textPadding; break; case WatermarkPositionEnum.LeftCenter: x = textPadding; y = (int)((originImage.Height / 2.0) - textSize.Height - textPadding); break; case WatermarkPositionEnum.LeftButtom: x = textPadding; y = originImage.Height - (int)textSize.Height - textPadding; break; case WatermarkPositionEnum.CenterTop: x = (int)((originImage.Width / 2) - textSize.Width - textPadding); y = textPadding; break; case WatermarkPositionEnum.Center: x = (int)((originImage.Width / 2) - textSize.Width - textPadding); y = originImage.Height - (int)textSize.Height - textPadding; break; case WatermarkPositionEnum.CenterButtom: x = (int)((originImage.Width / 2) - textSize.Width - textPadding); y = originImage.Height - (int)textSize.Height - textPadding; break; case WatermarkPositionEnum.RightTop: x = originImage.Width - (int)textSize.Width - textPadding; y = textPadding; break; case WatermarkPositionEnum.RightCenter: x = originImage.Width - (int)textSize.Width - textPadding; y = (int)((originImage.Height / 2.0) - textSize.Height - textPadding); break; case WatermarkPositionEnum.RightButtom: x = originImage.Width - (int)textSize.Width - textPadding; y = originImage.Height - (int)textSize.Height - textPadding; break; default: x = textPadding; y = textPadding; break; } graphic.DrawString(watermarkText, f, brush, new Point(x, y)); } ImageFormat fmt = null; switch (imgExtensionName) { case ".png": fmt = ImageFormat.Png; break; case ".jpg": case ".jpeg": fmt = ImageFormat.Jpeg; break; case ".bmp": fmt = ImageFormat.Bmp; break; default: fmt = ImageFormat.Jpeg; break; } var watermarkedStream = new MemoryStream(); originImage.Save(watermarkedStream, fmt); return(watermarkedStream); } }
/// <summary> /// Convert Bitmap Image to Base64 and Automatically Generate Image Url /// </summary> /// <param name="bmp"></param> /// <param name="imageformat"></param> /// <returns></returns> public static string ToBase64StringImgData(this Bitmap bmp, ImageFormat imageformat) { return(string.Format("data:image/{0};base64,{1}", imageformat.ToString(), bmp.ToBase64String(imageformat))); }
// Resize Image to FileUrl In Server public static string FileUploadAndResizeFromStream(string ImageSavePath, int MaxSideSize, Stream Buffer) { String sFileName = DTWebSettings.ConvertUtility.ToDateTimeFormat(DateTime.Now, "ddMMyyy_HHmmss") + ".jpg"; String sThuMucLuuFileTrenServer = ImageSavePath.Trim() + "/"; sThuMucLuuFileTrenServer += DateTime.Now.Year.ToString(); if (!Directory.Exists(new System.Web.UI.Page().Server.MapPath(DTWebSettings.ApplicationURL.Root + sThuMucLuuFileTrenServer))) { Directory.CreateDirectory(new System.Web.UI.Page().Server.MapPath(DTWebSettings.ApplicationURL.Root + sThuMucLuuFileTrenServer)); } sThuMucLuuFileTrenServer += "/" + DateTime.Now.Month.ToString(); if (!Directory.Exists(new System.Web.UI.Page().Server.MapPath(DTWebSettings.ApplicationURL.Root + sThuMucLuuFileTrenServer))) { Directory.CreateDirectory(new System.Web.UI.Page().Server.MapPath(DTWebSettings.ApplicationURL.Root + sThuMucLuuFileTrenServer)); } sThuMucLuuFileTrenServer += "/" + DateTime.Now.Day.ToString(); if (!Directory.Exists(new System.Web.UI.Page().Server.MapPath(DTWebSettings.ApplicationURL.Root + sThuMucLuuFileTrenServer))) { Directory.CreateDirectory(new System.Web.UI.Page().Server.MapPath(DTWebSettings.ApplicationURL.Root + sThuMucLuuFileTrenServer)); } sThuMucLuuFileTrenServer += "/" + sFileName.Trim(); int intNewWidth; int intNewHeight; System.Drawing.Image imgInput = System.Drawing.Image.FromStream(Buffer); //Determine image format ImageFormat fmtImageFormat = imgInput.RawFormat; //get image original width and height int intOldWidth = imgInput.Width; int intOldHeight = imgInput.Height; //determine if landscape or portrait int intMaxSide; if (intOldWidth >= intOldHeight) { intMaxSide = intOldWidth; } else { intMaxSide = intOldHeight; } if (intMaxSide > MaxSideSize) { //set new width and height double dblCoef = MaxSideSize / (double)intMaxSide; intNewWidth = Convert.ToInt32(dblCoef * intOldWidth); intNewHeight = Convert.ToInt32(dblCoef * intOldHeight); } else { intNewWidth = intOldWidth; intNewHeight = intOldHeight; } //create new bitmap Bitmap bmpResized = new Bitmap(imgInput, intNewWidth, intNewHeight); //save bitmap to disk bmpResized.Save(new System.Web.UI.Page().Server.MapPath(DTWebSettings.ApplicationURL.Root + sThuMucLuuFileTrenServer), fmtImageFormat); //release used resources imgInput.Dispose(); bmpResized.Dispose(); Buffer.Close(); return(sThuMucLuuFileTrenServer); }
public void Save(Bitmap Image, ImageFormat Format, string FileName, TextLocalizer Status, RecentViewModel Recents) { Image.WriteToClipboard(Format.Equals(ImageFormat.Png)); Status.LocalizationKey = nameof(Resources.ImgSavedClipboard); }
/// <summary> /// Method to get encoder infor for given sourceImage format. /// </summary> /// <param name="format">Image format</param> /// <returns>sourceImage codec info.</returns> private static ImageCodecInfo GetEncoderInfo(ImageFormat format) { var imageEncoders = ImageCodecInfo.GetImageEncoders(); return(imageEncoders.SingleOrDefault(c => c.FormatID.ToString() == format.Guid.ToString())); }