//=========================================================================================== private static MagickReadSettings CreateSettings() { MagickReadSettings settings = new MagickReadSettings(); settings.PixelStorage = new PixelStorageSettings(StorageType.Double, "RGBA"); settings.Width = 2; settings.Height = 1; return settings; }
public void Test_Collection_Exceptions() { using (MagickImageCollection collection = new MagickImageCollection()) { MagickReadSettings settings = new MagickReadSettings(); settings.PixelStorage = new PixelStorageSettings(); ExceptionAssert.Throws<ArgumentException>(delegate() { collection.Read(Files.RoseSparkleGIF, settings); }); } }
public void Test_Image_Read() { using (MagickImage image = new MagickImage()) { MagickReadSettings settings = new MagickReadSettings(); settings.Density = new MagickGeometry(300, 300); image.Read(Files.SnakewarePNG, settings); Assert.AreEqual(300, image.Density.Width); settings = null; image.Read(Files.ImageMagickJPG, settings); } }
public void Test_Collection_Read() { using (MagickImageCollection collection = new MagickImageCollection()) { MagickReadSettings settings = new MagickReadSettings(); settings.Density = new MagickGeometry(150, 150); collection.Read(Files.RoseSparkleGIF, settings); Assert.AreEqual(150, collection[0].Density.Width); settings = null; collection.Read(Files.RoseSparkleGIF, settings); } }
private void ProcessRAW(string[] srcRGBTriplet, ShotSetting[] shotSettings, string targetFilename, TARGETFORMAT targetFormat, FORMAT inputFormat, int maxThreads, float HDRClippingPoint, float HDRFeatherMultiplier, bool EXRIntegrityVerification) { int groupLength = shotSettings.Length; byte[][] buffers = new byte[groupLength][]; for (int i = 0; i < groupLength; i++) { buffers[i] = File.ReadAllBytes(srcRGBTriplet[i]); if (inputFormat == FORMAT.MONO12p) { buffers[i] = convert12pto16bit(buffers[i]); } } int width = 4096; int height = 3000; this.Dispatcher.Invoke(() => { width = 1; int.TryParse(rawWidth.Text, out width); height = 1; int.TryParse(rawHeight.Text, out height); }); byte[][] RGBBuffers = HDRMerge(buffers, shotSettings, HDRClippingPoint, HDRFeatherMultiplier); byte[] buffR = RGBBuffers[0]; byte[] buffG = RGBBuffers[1]; byte[] buffB = RGBBuffers[2]; // Interleave int pixelCount = width * height; int totalLength = width * height * 3; byte[] buff = new byte[totalLength * 2]; if (buffR.Count() < pixelCount * 2) { this.Dispatcher.Invoke(() => { MessageBox.Show("Red file too short: " + srcRGBTriplet[0]); }); return; } if (buffG.Count() < pixelCount * 2) { this.Dispatcher.Invoke(() => { MessageBox.Show("Green file too short: " + srcRGBTriplet[1]); }); return; } if (buffB.Count() < pixelCount * 2) { this.Dispatcher.Invoke(() => { MessageBox.Show("Blue file too short: " + srcRGBTriplet[2]); }); return; } for (int pixelIndex = 0; pixelIndex < pixelCount; pixelIndex++) { /* * // BGR * buff[pixelIndex * 3 * 2] = buffB[pixelIndex * 2]; * buff[pixelIndex * 3 * 2 + 1] = buffB[pixelIndex * 2 + 1]; * buff[pixelIndex * 3 * 2 +4] = buffR[pixelIndex*2]; * buff[pixelIndex * 3 * 2 +5] = buffR[pixelIndex * 2 + 1]; * buff[pixelIndex * 3 * 2 +2] = buffG[pixelIndex * 2]; * buff[pixelIndex * 3 * 2 +3] = buffG[pixelIndex * 2 + 1]; */ // RGB buff[pixelIndex * 3 * 2] = buffR[pixelIndex * 2]; buff[pixelIndex * 3 * 2 + 1] = buffR[pixelIndex * 2 + 1]; buff[pixelIndex * 3 * 2 + 2] = buffG[pixelIndex * 2]; buff[pixelIndex * 3 * 2 + 3] = buffG[pixelIndex * 2 + 1]; buff[pixelIndex * 3 * 2 + 4] = buffB[pixelIndex * 2]; buff[pixelIndex * 3 * 2 + 5] = buffB[pixelIndex * 2 + 1]; } string fileName = targetFilename; if (targetFormat == TARGETFORMAT.EXR) { ResourceLimits.Thread = (ulong)maxThreads; ResourceLimits.LimitMemory(new Percentage(90)); MagickReadSettings settings = new MagickReadSettings(); settings.Width = width; settings.Height = height; settings.Format = MagickFormat.Rgb; // Correction, this is actually right, I had flipped RGB to BGR elsewhere in the code before. Fixed now. /*ColorManager.ICC.ICCProfileWriter iccWriter = new ColorManager.ICC.ICCProfileWriter(); * iccWriter.WriteProfile(new ColorManager.ICC.ICCProfile()); */ if (EXRIntegrityVerification) { /* * Info on half float format: https://www.openexr.com/about.html */ // What does this mean for precision of converting 16 bit integers to 16 bit floating point? // We need to know the maximum precision achievable to be able to tell rounding errors from actual integrity fails. // More info here: https://en.wikipedia.org/wiki/Half-precision_floating-point_format // Basically, precision at any given value is 11 bits or 2048 values. int integrityCheckFailCountLocal = 0; bool integrityCheckPassed = false; bool retriesExhausted = false; while (!integrityCheckPassed && !retriesExhausted) { using (var image = new MagickImage(buff, settings)) { //ExifProfile profile = new ExifProfile(); //profile.SetValue(ExifTag.UserComment, Encoding.ASCII.GetBytes(srcRGBTriplet[0] + "," + srcRGBTriplet[1] + "," + srcRGBTriplet[2])); //image.SetProfile(profile); image.Format = MagickFormat.Exr; image.Settings.Compression = CompressionMethod.Piz; //image.Write(fileName); byte[] exrFile = image.ToByteArray(); bool integrityCheckFailed = false; using (var reloadedImage = new MagickImage(exrFile)) { reloadedImage.Depth = 16; reloadedImage.ColorSpace = ColorSpace.Undefined; byte[] reloadedImageBytes = reloadedImage.ToByteArray(MagickFormat.Rgb); integrityCheckFailed = integrityCheckFailed | !IntegrityChecker.VerifyIntegrityUInt16InHalfPrecisionFloat(buff, reloadedImageBytes); } if (integrityCheckFailed) { integrityCheckFailCount++; integrityCheckFailCountLocal++; continue; } else { integrityCheckPassed = true; File.WriteAllBytes(fileName, exrFile); } if (integrityCheckFailCountLocal > integrityCheckRetries) { retriesExhausted = true; // At this point just write it into a subfolder and be done with it. string failedFolder = Path.GetDirectoryName(fileName) + Path.DirectorySeparatorChar + "FAILED" + Path.DirectorySeparatorChar; Directory.CreateDirectory(failedFolder); string failedFile = failedFolder + Path.GetFileName(fileName); File.WriteAllBytes(failedFile, exrFile); } } } } else { using (var image = new MagickImage(buff, settings)) { //ExifProfile profile = new ExifProfile(); //profile.SetValue(ExifTag.UserComment, Encoding.ASCII.GetBytes(srcRGBTriplet[0] + "," + srcRGBTriplet[1] + "," + srcRGBTriplet[2])); //image.SetProfile(profile); image.Format = MagickFormat.Exr; image.Settings.Compression = CompressionMethod.Piz; //image.Write(fileName); byte[] exrFile = image.ToByteArray(); File.WriteAllBytes(fileName, exrFile); } } } else if (targetFormat == TARGETFORMAT.TIF) { using (Tiff output = Tiff.Open(fileName, "w")) { output.SetField(TiffTag.SUBFILETYPE, 0); //output.SetField(TiffTag.ORIGINALRAWFILENAME, srcRGBTriplet[0]+","+srcRGBTriplet[1]+","+srcRGBTriplet[2]); output.SetField(TiffTag.IMAGEWIDTH, width); output.SetField(TiffTag.IMAGELENGTH, height); output.SetField(TiffTag.SAMPLESPERPIXEL, 3); output.SetField(TiffTag.BITSPERSAMPLE, 16); output.SetField(TiffTag.ORIENTATION, Orientation.TOPLEFT); output.SetField(TiffTag.PHOTOMETRIC, Photometric.RGB); output.SetField(TiffTag.FILLORDER, FillOrder.MSB2LSB); output.SetField(TiffTag.COMPRESSION, Compression.DEFLATE); output.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG); output.WriteEncodedStrip(0, buff, width * height * 2 * 3); } } }
public async static Task <SaveImageThumbnailResult> SaveImageThumbnail(idCatalogItem catalogItem, IDImagerDB db, IDImagerThumbsDB dbThumbs, List <string> types, ServiceSettings serviceSettings) { SaveImageThumbnailResult result = new SaveImageThumbnailResult(); Stream imageStream = null; String filePath = null; try { filePath = GetImageFilePath(catalogItem, serviceSettings.FilePathReplace); imageStream = GetImageFileStream(filePath); foreach (String type in types) { int imageWidth; int imageHeight; if (type.Equals("T")) { imageWidth = 160; imageHeight = 120; } else { imageWidth = serviceSettings.MThumbmailWidth; imageHeight = serviceSettings.MThumbnailHeight; } XmpRecipeContainer xmpRecipeContainer = null; if (type.Equals("T") || type.Equals("R")) { if (catalogItem.idHasRecipe > 0) { XDocument recipeXDocument = await GetRecipeXDocument(db, catalogItem); xmpRecipeContainer = XmpRecipeHelper.ParseXmlRecepie(recipeXDocument); } } MemoryStream resizedImageStream = new MemoryStream(); MagickReadSettings magickReadSettings = null; if (Enum.TryParse <MagickFormat>(catalogItem.idFileType, true, out MagickFormat magickFormat)) { magickReadSettings = new MagickReadSettings { Format = magickFormat }; } imageStream.Position = 0; MagickImage image = new MagickImage(imageStream, magickReadSettings) { Format = MagickFormat.Jpeg, }; image.Resize(imageWidth, imageHeight); if (xmpRecipeContainer != null) { XmpRecipeHelper.ApplyXmpRecipe(xmpRecipeContainer, image); } image.Write(resizedImageStream); resizedImageStream.Position = 0; bool boolThumbExists = await dbThumbs.idThumbs .AnyAsync(x => x.ImageGUID == catalogItem.GUID && x.idType == type); if (!boolThumbExists) { idThumbs newThumb = new idThumbs { GUID = Guid.NewGuid().ToString().ToUpper(), ImageGUID = catalogItem.GUID, idThumb = StreamToByteArray(resizedImageStream), idType = type }; dbThumbs.idThumbs.Add(newThumb); } result.ImageStreams.Add(resizedImageStream); } if (imageStream != null) { imageStream.Close(); } await dbThumbs.SaveChangesAsync(); } catch (Exception ex) { if (imageStream != null) { imageStream.Close(); } result.Exceptions.Add(new Exception(String.Format("Error generating thumbnail for imageGUID {0} file {1}", catalogItem.GUID, filePath), ex)); } return(result); }
/// <summary> /// Load image from file /// </summary> /// <param name="filename">Full path of image file</param> /// <param name="size">A custom size of image</param> /// <param name="colorProfileName">Name or Full path of color profile</param> /// <param name="isApplyColorProfileForAll">If FALSE, only the images with embedded profile will be applied</param> /// <param name="quality">Image quality</param> /// <param name="channel">MagickImage.Channel value</param> /// <param name="useEmbeddedThumbnails">Return the embedded thumbnail if required size was not found.</param> /// <returns>Bitmap</returns> public static ImgData Load( string filename, Size size = new Size(), string colorProfileName = "sRGB", bool isApplyColorProfileForAll = false, int quality = 100, int channel = -1, bool useEmbeddedThumbnails = false ) { Bitmap bitmap = null; IExifProfile exif = null; IColorProfile colorProfile = null; var ext = Path.GetExtension(filename).ToUpperInvariant(); var settings = new MagickReadSettings(); #region Settings if (ext == ".SVG") { settings.BackgroundColor = MagickColors.Transparent; settings.SetDefine("svg:xml-parse-huge", "true"); } if (size.Width > 0 && size.Height > 0) { settings.Width = size.Width; settings.Height = size.Height; } // Fixed #708: length and filesize do not match settings.SetDefines(new BmpReadDefines { IgnoreFileSize = true, }); // Fix RAW color settings.SetDefines(new DngReadDefines() { UseCameraWhitebalance = true, }); #endregion #region Read image data switch (ext) { case ".TXT": // base64 string case ".B64": var base64Content = string.Empty; using (var fs = new StreamReader(filename)) { base64Content = fs.ReadToEnd(); } bitmap = ConvertBase64ToBitmap(base64Content); break; case ".GIF": case ".TIF": // Note: Using FileStream is much faster than using MagickImageCollection try { bitmap = ConvertFileToBitmap(filename); } catch { // #637: falls over with certain images, fallback to MagickImage ReadWithMagickImage(); } break; case ".ICO": case ".WEBP": case ".PDF": using (var imgColl = new MagickImageCollection(filename, settings)) { bitmap = imgColl.ToBitmap(); } break; default: ReadWithMagickImage(); break; } #endregion #region Internal Functions // Preprocess magick image (IExifProfile, IColorProfile) PreprocesMagickImage(MagickImage imgM, bool checkRotation = true) { imgM.Quality = quality; IColorProfile imgColorProfile = null; IExifProfile profile = null; try { // get the color profile of image imgColorProfile = imgM.GetColorProfile(); // Get Exif information profile = imgM.GetExifProfile(); } catch { } // Use embedded thumbnails if specified if (profile != null && useEmbeddedThumbnails) { // Fetch the embedded thumbnail var thumbM = profile.CreateThumbnail(); if (thumbM != null) { bitmap = thumbM.ToBitmap(); } } // Revert to source image if an embedded thumbnail with required size was not found. if (bitmap == null) { if (profile != null && checkRotation) { // Get Orientation Flag var exifRotationTag = profile.GetValue(ExifTag.Orientation); if (exifRotationTag != null) { if (int.TryParse(exifRotationTag.Value.ToString(), out var orientationFlag)) { var orientationDegree = Helpers.GetOrientationDegree(orientationFlag); if (orientationDegree != 0) { //Rotate image accordingly imgM.Rotate(orientationDegree); } } } } // if always apply color profile // or only apply color profile if there is an embedded profile if (isApplyColorProfileForAll || imgColorProfile != null) { if (imgColorProfile != null) { // correct the image color space imgM.ColorSpace = imgColorProfile.ColorSpace; } else { // set default color profile and color space imgM.SetProfile(ColorProfile.SRGB); imgM.ColorSpace = ColorProfile.SRGB.ColorSpace; } var imgColor = Helpers.GetColorProfile(colorProfileName); if (imgColor != null) { imgM.SetProfile(imgColor); imgM.ColorSpace = imgColor.ColorSpace; } } } return(profile, imgColorProfile); } // Separate color channel MagickImage ApplyColorChannel(MagickImage imgM) { if (channel != -1) { var magickChannel = (Channels)channel; var channelImgM = (MagickImage)imgM.Separate(magickChannel).First(); if (imgM.HasAlpha && magickChannel != Channels.Alpha) { using var alpha = imgM.Separate(Channels.Alpha).First(); channelImgM.Composite(alpha, CompositeOperator.CopyAlpha); } return(channelImgM); } return(imgM); } void ReadWithMagickImage() { MagickImage imgM; // Issue #530: ImageMagick falls over if the file path is longer than the (old) windows limit of 260 characters. Workaround is to read the file bytes, but that requires using the "long path name" prefix to succeed. if (filename.Length > 260) { var newFilename = Helpers.PrefixLongPath(filename); var allBytes = File.ReadAllBytes(newFilename); imgM = new MagickImage(allBytes, settings); } else { imgM = new MagickImage(filename, settings); } // Issue #679: fix targa display with Magick.NET 7.15.x if (ext == ".TGA") { imgM.AutoOrient(); } var checkRotation = ext != ".HEIC"; (exif, colorProfile) = PreprocesMagickImage(imgM, checkRotation); using (var channelImgM = ApplyColorChannel(imgM)) { bitmap = channelImgM.ToBitmap(); } imgM.Dispose(); } #endregion return(new ImgData() { Image = bitmap, Exif = exif, ColorProfile = colorProfile, }); }
public MagickImage ReadImage(MagickReadSettings settings) { return(new MagickImage(_fileName, settings)); }
/// <summary> /// Load image from file /// </summary> /// <param name="path">Full path of image file</param> /// <param name="width">Width value of scalable image format</param> /// <param name="height">Height value of scalable image format</param> /// <returns></returns> public static Bitmap Load(string path, int @width = 0, int @height = 0) { var ext = Path.GetExtension(path).ToLower(); Bitmap bmp = null; switch (ext) { case ".gif": using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { var ms = new MemoryStream(); fs.CopyTo(ms); ms.Position = 0; bmp = new Bitmap(ms, true); } break; case ".ico": bmp = ReadIconFile(path); break; default: try { GetBitmapFromFile(); if (bmp == null) { GetBitmapFromWic(); } } catch (Exception) { GetBitmapFromWic(); } break; } void GetBitmapFromFile() { var settings = new MagickReadSettings(); if (ext.CompareTo(".svg") == 0) { settings.BackgroundColor = MagickColors.Transparent; } if (width > 0 && height > 0) { settings.Width = width; settings.Height = height; } //using (var magicColl = new MagickImageCollection()) //{ // magicColl.Read(new FileInfo(path), settings); // if (magicColl.Count > 0) // { // magicColl[0].Quality = 100; // magicColl[0].AddProfile(ColorProfile.SRGB); // bmp = BitmapBooster.BitmapFromSource(magicColl[0].ToBitmapSource()); // } //} using (var magicImg = new MagickImage(path, settings)) { magicImg.Quality = 100; //Get Exif information var profile = magicImg.GetExifProfile(); if (profile != null) { //Get Orieantation Flag var exifTag = profile.GetValue(ExifTag.Orientation); if (exifTag != null) { int orientationFlag = int.Parse(profile.GetValue(ExifTag.Orientation).Value.ToString()); var orientationDegree = GetOrientationDegree(orientationFlag); if (orientationDegree != 0) { //Rotate image accordingly magicImg.Rotate(orientationDegree); } } } //corect the image color magicImg.AddProfile(ColorProfile.SRGB); //get bitmap bmp = magicImg.ToBitmap(); } } void GetBitmapFromWic() { var src = LoadImage(path); bmp = BitmapFromSource(src); } return(bmp); }
public static void pdf2image(Guid applicationId, DocFileInfo pdf, string password, DocFileInfo destFile, ImageFormat imageFormat, bool repair) { //MagickNET.SetGhostscriptDirectory("[GhostScript DLL Dir]"); //MagickNET.SetTempDirectory("[a temp dir]"); if (!pdf.FileID.HasValue) { return; } else if (PDF2ImageProcessing.ContainsKey(pdf.FileID.Value) && (!repair || PDF2ImageProcessing[pdf.FileID.Value])) { return; } else { PDF2ImageProcessing[pdf.FileID.Value] = true; } if (destFile.file_exists_in_folder(applicationId) && !repair) { PDF2ImageProcessing[pdf.FileID.Value] = false; return; } try { string cacheDir = PublicMethods.map_path(PublicConsts.MagickCacheDirectory, localPath: true); if (!Directory.Exists(cacheDir)) { Directory.CreateDirectory(cacheDir); } MagickAnyCPU.CacheDirectory = cacheDir; } catch (Exception ex) { LogController.save_error_log(applicationId, null, "SetMagickCacheDirectory", ex, ModuleIdentifier.DCT); } try { string tempDir = PublicMethods.map_path(PublicConsts.TempDirectory, localPath: true); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } MagickNET.SetTempDirectory(tempDir); if (!string.IsNullOrEmpty(RaaiVanSettings.GhostScriptDirectory)) { MagickNET.SetGhostscriptDirectory(RaaiVanSettings.GhostScriptDirectory); } } catch (Exception ex) { LogController.save_error_log(applicationId, null, "SetMagickTempDirectory", ex, ModuleIdentifier.DCT); } try { using (MagickImageCollection pages = new MagickImageCollection()) { MagickReadSettings settings = new MagickReadSettings() { Density = new Density(100, 100) }; bool invalidPassword = false; using (PdfReader reader = PDFUtil.open_pdf_file(applicationId, pdf, password, ref invalidPassword)) { byte[] pdfContent = PDFUtil.to_byte_array(reader); pages.Read(pdfContent, settings); } int pageNum = 0; bool errorLoged = false; foreach (MagickImage p in pages) { ++pageNum; destFile.FileName = pageNum.ToString(); destFile.Extension = imageFormat.ToString().ToLower(); if (destFile.exists(applicationId)) { continue; } try { using (MemoryStream stream = new MemoryStream()) { p.ToBitmap(imageFormat).Save(stream, imageFormat); destFile.store(applicationId, stream.ToArray()); } } catch (Exception ex) { if (!errorLoged) { errorLoged = true; LogController.save_error_log(applicationId, null, "ConvertPDFPageToImage", ex, ModuleIdentifier.DCT); } } } } } catch (Exception ex) { LogController.save_error_log(applicationId, null, "ConvertPDFToImage", ex, ModuleIdentifier.DCT); } PDF2ImageProcessing[pdf.FileID.Value] = false; }
public void Extract_DefaultValueIsNull() { var settings = new MagickReadSettings(); Assert.Null(settings.ExtractArea); }
/// <summary> /// [Phap] Creates a thumbnail from the given image file. /// </summary> /// <param name="filename">The filename pointing to an image.</param> /// <param name="size">Requested image size.</param> /// <param name="useEmbeddedThumbnails">Embedded thumbnail usage.</param> /// <param name="rotate">Rotation angle.</param> /// <returns>The image from the given file or null if an error occurs.</returns> internal static Image GetThumbnailBmp(string filename, Size size, UseEmbeddedThumbnails useEmbeddedThumbnails, int rotate) { if (size.Width <= 0 || size.Height <= 0) { throw new ArgumentException(); } Image source = null; Image thumb = null; var ext = Path.GetExtension(filename).ToLower(); try { var settings = new MagickReadSettings(); if (ext.CompareTo(".svg") == 0) { settings.BackgroundColor = MagickColors.Transparent; } if (size.Width > 0 && size.Height > 0) { settings.Width = size.Width; settings.Height = size.Height; } using (var magicImg = new MagickImage(filename, settings)) { // Try to read the exif thumbnail if (useEmbeddedThumbnails != UseEmbeddedThumbnails.Never) { var profile = magicImg.GetExifProfile(); if (profile != null) { // Fetch the embedded thumbnail var magicThumb = profile.CreateThumbnail(); if (magicThumb != null) { source = magicThumb.ToBitmap(); if (useEmbeddedThumbnails == UseEmbeddedThumbnails.Auto) { // Check that the embedded thumbnail is large enough. if (Math.Max((float)source.Width / (float)size.Width, (float)source.Height / (float)size.Height) < 1.0f) { source.Dispose(); source = null; } } } } } // Revert to source image if an embedded thumbnail of required size was not found. if (source == null) { source = magicImg.ToBitmap(); } }//END using MagickImage } catch { source = null; } // If all failed, return null. if (source == null) { return(null); } // Create the thumbnail try { double scale; if (rotate % 180 != 0) { scale = Math.Min(size.Height / (double)source.Width, size.Width / (double)source.Height); } else { scale = Math.Min(size.Width / (double)source.Width, size.Height / (double)source.Height); } thumb = ScaleDownRotateBitmap(source, scale, rotate); } catch { if (thumb != null) { thumb.Dispose(); } thumb = null; } finally { if (source != null) { source.Dispose(); } source = null; } return(thumb); }
private void UpdateImage() { PrepareImage(); if (cbImageSize.SelectedItem == null) { return; } //backgorund image var background = ((TileSize)cbImageSize.SelectedItem); //text information var textBackgroundColor = btTextColor.BackColor; var textAlignment = (TileAlignment)Enum.Parse(typeof(TileAlignment), cbTextAlignment.SelectedValue.ToString()); var textPosition = (TilePosition)Enum.Parse(typeof(TilePosition), cbTextPosition.SelectedValue.ToString()); var textMarginHorizontal = trackTextHorizontal.Value; var textMarginVertical = trackTextVertical.Value; var textVisible = checkTextEnabled.Checked; var textFontSize = (int)TextSize.Value; var textText = txtTexto.Text; _TileText = new TileText( textText, textFontSize, background, textBackgroundColor, textAlignment, textPosition, textMarginHorizontal, textMarginVertical, textVisible); var iconBackgroundColor = colorBackgound.Color; var iconSize = (int)cbIconSize.SelectedItem; var iconColor = cbIconColor.SelectedItem.ToString(); var iconAlignment = (TileAlignment)Enum.Parse(typeof(TileAlignment), cbIconAlignment.SelectedValue.ToString()); var iconPosition = (TilePosition)Enum.Parse(typeof(TilePosition), cbIconPosition.SelectedValue.ToString()); var iconMarginHorizontal = trackIconHorizontal.Value; var iconMarginVertical = trackIconVertical.Value; var iconName = cbIconImage.SelectedItem.ToString(); _TileIcon = new TileIcon( iconName, background, iconBackgroundColor, iconColor, iconSize, iconAlignment, iconPosition, iconMarginHorizontal, iconMarginVertical, true); MagickReadSettings settings = new MagickReadSettings(); settings.Width = pictureBox1.Width = background.Width; settings.Height = pictureBox1.Height = background.Height; using (MemoryStream memStream = new MemoryStream()) { using (MagickImage image = new MagickImage($"xc: rgb({_TileIcon.BackgroundColor.R},{_TileIcon.BackgroundColor.G},{_TileIcon.BackgroundColor.B})", settings)) { image.Format = MagickFormat.Png; image.Composite(new MagickImage(_TileIcon.Path), _TileIcon.GetX(), _TileIcon.GetY(), CompositeOperator.Blend); //draw Text if (_TileText.IsVisible()) { new Drawables() .FontPointSize(_TileText.FontSize) .Font(_TileText.Font) .StrokeColor(_TileText.Color) .FillColor(_TileText.BackgroundColor) .TextAlignment(_TileText.GetAlignmentAsTextAlignment()) .Text(_TileText.GetX(), _TileText.GetY(), _TileText.Text) .Draw(image); } image.Write(DefaultImage); } } using (Image myImage = Image.FromFile(DefaultImage)) { pictureBox1.Image = (Image)myImage.Clone(); pictureBox1.Update(); } }
public void ShouldThrowExceptionWhenDataIsEmpty() { var settings = new MagickReadSettings(); Assert.Throws <ArgumentException>("data", () => new MagickImage(Span <byte> .Empty, settings)); }
public MagickImage ToMagickImage(MagickReadSettings settings = null) { return(GetMagickImage.Invoke(Data, settings)); }
internal PixelReadSettings() { ReadSettings = new MagickReadSettings(); }
public void handle_objecvtive_formula(string command) { GObject tmp = null; GObject tmp_up = null; GObject tmp_down = null; formula_container.objects = new List <GObject>(); int j = 0; int length = command.Length; while (j < length) { string t = ""; tmp = new GObject(); tmp_up = new GObject(); tmp_down = new GObject(); while (command[j] != '.') { t += command[j]; j++; } if (t == "INT") { tmp.symbol = StringMaker.symbol_maker("∫ ", 1); tmp.id = SYMBOL.GO_INT; } else if (t == "SUM") { tmp.symbol = StringMaker.symbol_maker("Σ ", 1); tmp.id = SYMBOL.GO_SUM; } else if (t == "FRC") { tmp.symbol = "FRCT_TMP_SYMBOL"; tmp.id = SYMBOL.GO_FRC; } else { int ind = is_in(t, custom_registered_GObjects_user_commands); tmp.symbol = custom_registered_GObjects[ind].symbol; } j++; t = ""; while (command[j] != ',') { t += command[j]; j++; } j++; tmp.main = t; tmp.up_child = false; tmp.down_child = false; t = ""; //up if (command[j] == '{') { j++; tmp.up_child = true; GObject new_tmp = new GObject(); GObject new_tmp_up = new GObject(); GObject new_tmp_down = new GObject(); tmp.up = new_tmp; tmp.up.up = new_tmp_up; tmp.up.down = new_tmp_down; while (command[j] != '}') { while (command[j] != '.') { t += command[j]; j++; } if (t == "INT") { tmp.up.symbol = StringMaker.symbol_maker("∫ ", 1); tmp.up.id = SYMBOL.GO_INT; } else if (t == "SUM") { tmp.up.symbol = StringMaker.symbol_maker("Σ ", 1); tmp.up.id = SYMBOL.GO_SUM; } else if (t == "FRC") { tmp.up.symbol = "FRCT_TMP_SYMBOL"; tmp.up.id = SYMBOL.GO_FRC; } j++; t = ""; while (command[j] != ',') { t += command[j]; j++; } j++; tmp.up.main = t; t = ""; while (command[j] != ',') { t += command[j]; j++; } j++; tmp.up.up.main = t; t = ""; while (command[j] != ';') { t += command[j]; j++; } j++; tmp.up.down.main = t; t = ""; } j += 2; if (tmp.up.id == SYMBOL.GO_FRC) { PDF_Maker.Fraction frcc = new PDF_Maker.Fraction(); PDF_Maker._Fraction_detail frc_det = frcc.fraction(tmp.up.up.main, tmp.up.down.main); tmp.up.symbol = frc_det.symbol; PDF_Maker.FRC_UP_DOWN fud = frcc.sort_fraction(frc_det); tmp.up.up.main = fud.uup; tmp.up.down.main = fud.ddown; } } else { tmp.up_child = false; while (command[j] != ',') { t += command[j]; j++; } j++; tmp.up = tmp_up; tmp.up.main = t; t = ""; } //down if (command[j] == '{') { j++; tmp.down_child = true; GObject new_tmp = new GObject(); GObject new_tmp_up = new GObject(); GObject new_tmp_down = new GObject(); tmp.down = new_tmp; tmp.down.up = new_tmp_up; tmp.down.down = new_tmp_down; while (command[j] != '}') { while (command[j] != '.') { t += command[j]; j++; } if (t == "INT") { tmp.down.symbol = StringMaker.symbol_maker("∫ ", 1); tmp.down.id = SYMBOL.GO_INT; } else if (t == "SUM") { tmp.down.symbol = StringMaker.symbol_maker("Σ ", 1); tmp.down.id = SYMBOL.GO_SUM; } else if (t == "FRC") { tmp.down.symbol = "FRCT_TMP_SYMBOL"; tmp.down.id = SYMBOL.GO_FRC; } j++; t = ""; while (command[j] != ',') { t += command[j]; j++; } j++; tmp.down.main = t; t = ""; while (command[j] != ',') { t += command[j]; j++; } j++; tmp.down.up.main = t; t = ""; while (command[j] != ';') { t += command[j]; j++; } j++; tmp.down.down.main = t; t = ""; } j += 2; if (tmp.down.id == SYMBOL.GO_FRC) { PDF_Maker.Fraction frcc = new PDF_Maker.Fraction(); PDF_Maker._Fraction_detail frc_det = frcc.fraction(tmp.down.up.main, tmp.down.down.main); tmp.down.symbol = frc_det.symbol; PDF_Maker.FRC_UP_DOWN fud = frcc.sort_fraction(frc_det); tmp.down.up.main = fud.uup; tmp.down.down.main = fud.ddown; } } else { tmp.down_child = false; while (command[j] != ';') { t += command[j]; j++; } j++; tmp.down = tmp_down; tmp.down.main = t; t = ""; } /////////////////////////// if (tmp.id == SYMBOL.GO_FRC) { PDF_Maker.Fraction frcc = new PDF_Maker.Fraction(); PDF_Maker._Fraction_detail frc_det = frcc.fraction(tmp.up.main, tmp.down.main); tmp.symbol = frc_det.symbol; PDF_Maker.FRC_UP_DOWN fud = frcc.sort_fraction(frc_det); tmp.up.main = fud.uup; tmp.down.main = fud.ddown; } formula_container.objects.Add(tmp); t = ""; tmp_down = null; tmp_up = null; tmp = null; } PdfSharp_PNG_handling(); MagickReadSettings settings = new MagickReadSettings(); settings.Density = new Density(500, 500); using (MagickImageCollection images = new MagickImageCollection()) { images.Read("__internal_ObjectiveFormula.pdf", settings); foreach (MagickImage image in images) { image.Write("__internal_ObjectiveFormula" + Global_Formula_Counter.Counter.cntr.ToString() + ".png"); image.Format = MagickFormat.Ptif; System.IO.File.Delete("__internal_ObjectiveFormula.pdf"); } } }
internal PixelStorageSettings() { ReadSettings = new MagickReadSettings(); }
/// <summary> /// /// </summary> /// <returns></returns> public MagickImage getImg(String inputPath, String type) { MagickImage mmm = null; if (M.c_影像.func_判斷_RAW(type)) { string dcRawExe = M.fun_執行檔路徑() + "/data/dcraw-9.27-ms-32-bit.exe"; var startInfo = new System.Diagnostics.ProcessStartInfo(dcRawExe) { Arguments = "-c -e \"" + inputPath + "\"", RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; try { using (var process = System.Diagnostics.Process.Start(startInfo)) { Stream st = process.StandardOutput.BaseStream; var memoryStream = new MemoryStream(); st.CopyTo(memoryStream); memoryStream.Position = 0; if (type == "X3F") { mmm = new MagickImage(new System.Drawing.Bitmap(memoryStream)); } else { mmm = new MagickImage((memoryStream)); } } } catch (Exception e) { Log.print("MagickImage錯誤" + e.ToString()); } } else if (type == "CR2") { //raw。必須從stream讀取圖片,不然會有BUG using (FileStream logFileStream = new FileStream(inputPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { mmm = new MagickImage(logFileStream); } } else if (type == "PDF" || type == "SVG" || type == "AI" || type == "WMF" || type == "EMF") { //設定輸出的解析度,用於向量圖片(svg、ai、pdf MagickReadSettings settings = new MagickReadSettings(); settings.Density = new Density(300, 300); mmm = new MagickImage(inputPath, settings); } else { //一般 mmm = new MagickImage(inputPath); } //矯正顏色 // Adding the second profile will transform the colorspace from CMYK to RGB if (mmm.GetColorProfile() != null) { if (mmm.GetColorProfile().Model != null) { mmm.AddProfile(ColorProfile.SRGB); } else { } } else { mmm.AddProfile(ColorProfile.SRGB); } return(mmm); }
private void AddEmote(string emoteName, Library.ILibraryInternal library, string url) { if (loadedEmotes.Contains(emoteName)) { return; } string encodedEmoteName = Utility.EncodeStringForFileName(emoteName); byte[] data = null; if (Library.FolderExists(TWITCH_CACHE_PATH)) { var qualifiedFilename = string.Format("{0}{1}", TWITCH_CACHE_PATH, encodedEmoteName); if (Library.FileExists(qualifiedFilename)) { data = File.ReadAllBytes(Library.GetFilename(qualifiedFilename)); } } MemoryStream imageStream = new MemoryStream(); if (data == null) { data = client.DownloadData(url); var folder = Library.GetFolderName(TWITCH_CACHE_PATH); MagickReadSettings settings = new MagickReadSettings(); settings.ColorSpace = ColorSpace.sRGB; settings.SetDefine(MagickFormat.Png, "format", "png8"); MagickImageInfo mImageInfo = new MagickImageInfo(data); if (mImageInfo.Format != MagickFormat.Gif) { using (MagickImage mImage = new MagickImage(data, settings)) { mImage.Write(imageStream); imageStream.Position = 0; } } else { using (MagickImageCollection mImages = new MagickImageCollection(data, settings)) { //Background is PepePls //SourPls is None var width = mImages.Max(x => x.Page.Width); var height = mImages.Max(y => y.Page.Height); FramePacker.FrameDisposal frameDisposal; switch (mImages[0].GifDisposeMethod) { case GifDisposeMethod.None: frameDisposal = FramePacker.FrameDisposal.Composite; break; case GifDisposeMethod.Undefined: case GifDisposeMethod.Background: case GifDisposeMethod.Previous: default: frameDisposal = FramePacker.FrameDisposal.Replace; break; } var packedImage = FramePacker.PackListOfImagesToMemStream( mImages.Select(imageFrame => new FramePacker.Frame { Image = imageFrame.ToBitmap(ImageFormat.Png), X = imageFrame.Page.X, Y = imageFrame.Page.Y, Width = imageFrame.BaseWidth, Height = imageFrame.BaseHeight }).ToArray(), imageStream, width, height, frameDisposal ); packedImage.FPS = 1 / ((float)mImages.Select(x => x.AnimationDelay).Average() / 100.0f); JsonWriter.Save(packedImage, string.Format("{0}{1}", TWITCH_CACHE_PATH, encodedEmoteName), true); //mImages[0].Write(imageStream); imageStream.Position = 0; } } File.WriteAllBytes(string.Format("{0}/{1}", folder, encodedEmoteName), data = imageStream.ToArray()); } library.AddTexture(string.Format("twitch//{0}", emoteName), imageStream); loadedEmotes.Add(emoteName); }
/// <summary> /// Converts base64 string to Bitmap. /// </summary> /// <param name="content">Base64 string</param> /// <returns></returns> public static Bitmap ConvertBase64ToBitmap(string content) { var(mimeType, rawData) = ConvertBase64ToBytes(content); if (string.IsNullOrEmpty(mimeType)) { return(null); } #region Settings var settings = new MagickReadSettings(); switch (mimeType) { case "image/bmp": settings.Format = MagickFormat.Bmp; break; case "image/gif": settings.Format = MagickFormat.Gif; break; case "image/tiff": settings.Format = MagickFormat.Tiff; break; case "image/jpeg": settings.Format = MagickFormat.Jpeg; break; case "image/svg+xml": settings.BackgroundColor = MagickColors.Transparent; settings.Format = MagickFormat.Svg; break; case "image/x-icon": settings.Format = MagickFormat.Ico; break; case "image/x-portable-anymap": settings.Format = MagickFormat.Pnm; break; case "image/x-portable-bitmap": settings.Format = MagickFormat.Pbm; break; case "image/x-portable-graymap": settings.Format = MagickFormat.Pgm; break; case "image/x-portable-pixmap": settings.Format = MagickFormat.Ppm; break; case "image/x-xbitmap": settings.Format = MagickFormat.Xbm; break; case "image/x-xpixmap": settings.Format = MagickFormat.Xpm; break; case "image/x-cmu-raster": settings.Format = MagickFormat.Ras; break; } #endregion Bitmap bmp = null; switch (settings.Format) { case MagickFormat.Gif: case MagickFormat.Gif87: case MagickFormat.Tif: case MagickFormat.Tiff64: case MagickFormat.Tiff: case MagickFormat.Ico: case MagickFormat.Icon: bmp = new Bitmap(new MemoryStream(rawData) { Position = 0 }, true); break; default: using (var imgM = new MagickImage(rawData, settings)) { bmp = imgM.ToBitmap(); } break; } return(bmp); }
private MagickImage RenderFrame(Image rawFrameImage, ConstAnimationFrame frameAnimationInfo, int smallestX, int largestX, int smallestY, int largestY, int normalizedWidth, int normalizedHeight) { MagickImage renderedFrame = new MagickImage(new MagickColor(0, 0, 0, 0), normalizedWidth, normalizedHeight); int normalizedFrameX = rawFrameImage.Attributes.LocationX - smallestX; int normalizedFrameY = rawFrameImage.Attributes.LocationY - smallestY; if (rawFrameImage.PixelData.Length > 0) { MagickReadSettings pixelDataSettings = new MagickReadSettings() { ColorSpace = ColorSpace.RGB, Width = rawFrameImage.Attributes.Width, Height = rawFrameImage.Attributes.Height, PixelStorage = new PixelStorageSettings(StorageType.Char, "RGBA") }; using (MagickImage rawFrameMagickImage = new MagickImage(rawFrameImage.PixelData, pixelDataSettings)) { rawFrameMagickImage.Format = MagickFormat.Gif; rawFrameMagickImage.MatteColor = new MagickColor(0, 0, 0, 0); renderedFrame.Composite(rawFrameMagickImage, normalizedFrameX, normalizedFrameY, CompositeOperator.Over); } } renderedFrame.Format = MagickFormat.Gif; renderedFrame.AnimationDelay = frameAnimationInfo.DelayInMs / 10; renderedFrame.GifDisposeMethod = GifDisposeMethod.Background; renderedFrame.AnimationIterations = 0; renderedFrame.MatteColor = new MagickColor(0, 0, 0, 0); return renderedFrame; }
/// <summary> /// Decodes image from file to BitMapSource /// </summary> /// <param name="file">Absolute path of the file</param> /// <returns></returns> internal static BitmapSource RenderToBitmapSource(string file) { var ext = Path.GetExtension(file).ToLower(CultureInfo.CurrentCulture); switch (ext) { // Skia supports? https://docs.microsoft.com/en-us/dotnet/api/skiasharp.skimageencodeformat?view=skiasharp-1.59.3 case ".jpg": case ".jpeg": case ".jpe": case ".png": case ".bmp": case ".tif": case ".tiff": case ".gif": case ".ico": case ".wdp": case ".jfif": case ".ktx": case ".webp": case ".wbmp": try { using var filestream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan); var sKBitmap = SKBitmap.Decode(filestream); if (sKBitmap == null) { return(null); } var pic = sKBitmap.ToWriteableBitmap(); pic.Freeze(); sKBitmap.Dispose(); return(pic); } catch (Exception e) { #if DEBUG Trace.WriteLine("RenderToBitmapSource exception: " + e.Message); #endif return(null); } default: using (MagickImage magick = new MagickImage()) { var mrs = new MagickReadSettings() { Density = new Density(300, 300), BackgroundColor = MagickColors.Transparent, }; try { using var filestream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, FileOptions.SequentialScan); magick.Read(filestream, mrs); } catch (MagickException e) { #if DEBUG Trace.WriteLine("GetMagickImage returned " + file + " null, \n" + e.Message); #endif return(null); } // Set values for maximum quality magick.Quality = 100; magick.ColorSpace = ColorSpace.Transparent; var pic = magick.ToBitmapSource(); pic.Freeze(); magick.Dispose(); return(pic); } } ; }