public void WriteFile(OutputType outputType, Stream stream) { using (var bitmap = new FreeImageBitmap(Width, Height, Width * 4, PixelFormat.Format32bppArgb, bitsHandle.AddrOfPinnedObject())) { switch (outputType) { case OutputType.JPEG: // JPEG_QUALITYGOOD is 75 JPEG. // JPEG_BASELINE strips metadata (EXIF, etc.) bitmap.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD | FREE_IMAGE_SAVE_FLAGS.JPEG_BASELINE); break; case OutputType.PNG: bitmap.Save(stream, FREE_IMAGE_FORMAT.FIF_PNG); break; case OutputType.Bitmap: bitmap.Save(stream, FREE_IMAGE_FORMAT.FIF_BMP); break; default: throw new ArgumentOutOfRangeException("outputType"); } } }
void fullSizeButton_MouseButtonClick(Widget source, EventArgs e) { if (currentImage != null) { String windowName = imageName.OnlyText; if (windowName == null) { windowName = ""; } String extension; FREE_IMAGE_FORMAT imageOutputFormat; getImageFormat(out extension, out imageOutputFormat); //Save the image as a temporary file and open it with the system file viewer String imageFile = String.Format("{0}/TempImage{1}", MedicalConfig.UserDocRoot, extension); try { using (Stream stream = File.Open(imageFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { currentImage.Save(stream, imageOutputFormat); } OtherProcessManager.openLocalURL(imageFile); } catch (Exception ex) { MessageBox.show(String.Format("Error writing the preview file to {0}.\nReason: {2}", imageFile, MedicalConfig.ImageOutputFolder, ex.Message), "Save Error", MessageBoxStyle.IconError | MessageBoxStyle.Ok); } } }
/** * Outputs displayable image of image channel to be corrected. * @param layer the channel corrected * @return true if successful **/ private void outputDisplayableBase(int layer) { float[] array; int width = base_dimensions[0]; int height = base_dimensions[1]; float value, value16bpp; string image_name = (string)dropdown_imageLayer.Items[layer]; array = new float[width * height]; Array.Copy(base_data, width * height * layer, array, 0, width * height); FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_TIFF; FREE_IMAGE_TYPE type = FREE_IMAGE_TYPE.FIT_FLOAT; FREE_IMAGE_SAVE_FLAGS save_flags = FREE_IMAGE_SAVE_FLAGS.TIFF_NONE; FreeImageBitmap image = new FreeImageBitmap(width, height, type); float maxValue = Enumerable.Range(0, array.Length).Max(m => array[m]); float minValue = Enumerable.Range(0, array.Length).Min(m => array[m]); for (int j = 0; j < height; ++j) { Scanline <float> scanline = image.GetScanline <float>(j); for (int k = 0; k < width; ++k) { value = array[width * j + k]; value16bpp = (1.0f / (maxValue - minValue) * (value - minValue)); scanline.SetValue(value16bpp, k); } } image.RotateFlip(base_orientation); image.Save("./Workspace/" + image_name + "_base_displayable.tiff", format, save_flags); }
public void Export(RadBitmap image, Stream stream) { Bitmap bitmap = image.ToBitmap(); FreeImageBitmap freeImageBitmap = new FreeImageBitmap(bitmap); freeImageBitmap.Save(stream, this.GetImageFormat()); }
/// <summary> /// Save the image to a file. Simplifies creating a stream, good for debugging. /// </summary> /// <param name="bitmap">The bitmap.</param> /// <param name="fileName">The name of the file to save.</param> /// <param name="format">The format to save the file in.</param> public static void saveToFile(this FreeImageBitmap bitmap, String fileName, FREE_IMAGE_FORMAT format) { using (Stream test = File.Open(fileName, FileMode.Create)) { bitmap.Save(test, format); } }
public void FreeImageFileFile() { using var output = TestFiles.OutputJpg(); using var image = FreeImageBitmap.FromFile(TestFiles.InputJpg); using var resized = new FreeImageBitmap(image, Width, Height); resized.Save(output.Path, FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD); }
public static void Compress(string image) { byte[] bytes = Convert.FromBase64String(image.Split(',')[1]); using (Stream stream = new MemoryStream(bytes)) { const int size = 150; using (var original = FreeImageBitmap.FromStream(stream)) { int width, height; if (original.Width > original.Height) { width = size; height = original.Height * size / original.Width; } else { width = original.Width * size / original.Height; height = size; } var resized = new FreeImageBitmap(original, width, height); Stream newStream = new MemoryStream(); resized.Save(newStream, FREE_IMAGE_FORMAT.FIF_JPEG); var newBytes = ReadFully(newStream); var contents = new StreamContent(new MemoryStream(newBytes)); } } }
public static void Main(string[] args) { var icoFile = args[1]; var fiBitmap = new FreeImageBitmap(args[0]); var first = true; foreach (var size in Sizes) { if (fiBitmap.Width < size || fiBitmap.Height < size) { continue; } fiBitmap.Rescale(size, size, FREE_IMAGE_FILTER.FILTER_BICUBIC); if (first) { first = false; fiBitmap.Save(icoFile); } else { fiBitmap.SaveAdd(icoFile); } } }
/// <summary> /// Compressing Image /// </summary> /// <param name="imagePath">Path to image</param> /// <param name="size">Size to compress</param> /// <returns>Compressing result</returns> public static bool CompressImage(string imagePath, int size) { try { //string newFile = imagePath.Replace(".jpg", ".new"); using (var original = FreeImageBitmap.FromFile(imagePath + ".new")) { int width, height; if (original.Width > original.Height) { width = size; height = original.Height * size / original.Width; } else { width = original.Width * size / original.Height; height = size; } var resized = new FreeImageBitmap(original, width, height); // JPEG_QUALITYGOOD is 75 JPEG. // JPEG_BASELINE strips metadata (EXIF, etc.) resized.Save(imagePath + ".jpg", FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD | FREE_IMAGE_SAVE_FLAGS.JPEG_BASELINE); } System.IO.File.Delete(imagePath + ".new"); return(true); } catch (Exception ex) { return(false); } }
public void getInfo(SaveInfo info) { info.AddValue(BONE_MANIPULATOR_STATE, boneState); info.AddValue(DISC_STATE, discState); info.AddValue(TEETH_STATE, teethState); info.AddValue(FOSSA_STATE, fossaState); info.AddValue(NOTES, notes); info.AddValue(NAME, Name); try //This isn't really a fix for why this fails sometimes, but it at least keeps it from crashing the whole program. { if (thumbnail != null) { using (MemoryStream memStream = new MemoryStream()) { thumbnail.Save(memStream, FREE_IMAGE_FORMAT.FIF_PNG); info.AddValue(THUMBNAIL, memStream.GetBuffer()); memStream.Close(); } } } catch (Exception e) { Log.Error("Error saving image for medical state {0}. Reason\n{1}.", Name, e.Message); } }
public void SaveAdd() { string filename = @"saveadd.tif"; FreeImageBitmap fib = new FreeImageBitmap(100, 100, PixelFormat.Format24bppRgb); try { fib.SaveAdd(); Assert.Fail(); } catch { } Assert.IsFalse(File.Exists(filename)); fib.Save(filename); fib.AdjustBrightness(0.3d); fib.SaveAdd(); FreeImageBitmap other = new FreeImageBitmap(100, 100, PixelFormat.Format24bppRgb); foreach (Scanline <RGBTRIPLE> scanline in other) { for (int i = 0; i < scanline.Length; i++) { scanline[i] = new RGBTRIPLE(Color.FromArgb(0x339955)); } } fib.SaveAdd(other); other.SaveAdd(filename); other.Dispose(); fib.Dispose(); fib = new FreeImageBitmap(filename); Assert.AreEqual(4, fib.FrameCount); fib.Dispose(); File.Delete(filename); Assert.IsFalse(File.Exists(filename)); }
public void Export(RadBitmap image, Stream stream) { Bitmap bitmap = image.ToBitmap(); FreeImageBitmap freeImageBitmap = new FreeImageBitmap(bitmap); freeImageBitmap.Save(stream, this.GetImageFormat()); }
/** * Outputs .tiff file to be read into Argo Solution as input parameter * @param layer the channel corrected * @return true if successful **/ private bool outputBase(int layer) { float[] array; int width = base_dimensions[0]; int height = base_dimensions[1]; float value; if (layer == -1) { return(false); } string image_name = (string)dropdown_imageLayer.Items[layer]; array = new float[width * height]; Array.Copy(base_data, width * height * layer, array, 0, width * height); FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_TIFF; FREE_IMAGE_TYPE type = FREE_IMAGE_TYPE.FIT_FLOAT; FREE_IMAGE_SAVE_FLAGS save_flags = FREE_IMAGE_SAVE_FLAGS.TIFF_NONE; FreeImageBitmap image = new FreeImageBitmap(width, height, type); for (int j = 0; j < height; ++j) { Scanline <float> scanline = image.GetScanline <float>(j); for (int k = 0; k < width; ++k) { value = array[width * j + k]; scanline.SetValue(value, k); } } image.RotateFlip(base_orientation); image.Save("./Workspace/" + image_name + "_base.tiff", format, save_flags); return(true); }
public static void SaveImage(Stream stream, FreeImageBitmap bitmap) { AjpHeader ajpHeaderFromBitmap = bitmap.Tag as AjpHeader; AjpHeader ajpHeaderFromComment = null; if (!string.IsNullOrEmpty(bitmap.Comment)) { ajpHeaderFromComment = new AjpHeader(); if (!ajpHeaderFromComment.ParseComment(bitmap.Comment)) { ajpHeaderFromComment = null; } } var ms = new MemoryStream(); var ms2 = new MemoryStream(); bitmap.Save(ms, FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE | FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD); using (var alpha = bitmap.GetChannel(FREE_IMAGE_COLOR_CHANNEL.FICC_ALPHA)) { if (alpha != null) { alpha.Comment = "signature = 19792, version = 2, headerSize = 64, colorDepth = 8"; Pms.SaveImage(ms2, alpha); } } AjpHeader ajpHeader = ajpHeaderFromBitmap; if (ajpHeader == null) { ajpHeader = ajpHeaderFromComment; } SaveImage(stream, ms.ToArray(), ms2.ToArray(), ajpHeader); }
private void saveImage(FreeImageBitmap source, String destFile, FREE_IMAGE_FORMAT format) { using (Stream outStream = File.Open(destFile, FileMode.Create, FileAccess.ReadWrite, FileShare.None)) { source.Save(outStream, format); } Log.Info("Wrote {0}", destFile); }
public void FreeImageBufferBuffer() { using var ims = new MemoryStream(buffer); using var image = FreeImageBitmap.FromStream(ims); using var resized = new FreeImageBitmap(image, Width, Height); using var oms = new MemoryStream(); resized.Save(oms, FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD); oms.ToArray(); }
public static byte[] GenerateJPEGBuffer(Bitmap original) { using (var stream = new MemoryStream(original.Width * 4 * original.Height / 8)) using (var freeImage = new FreeImageBitmap(original)) { freeImage.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB); return(stream.ToArray()); } }
public static byte[] GeneratePNGBuffer(Bitmap original) { using (var stream = new MemoryStream(original.Width * 4 * original.Height / 8)) using (var freeImage = new FreeImageBitmap(original)) { freeImage.Save(stream, FREE_IMAGE_FORMAT.FIF_PNG, FREE_IMAGE_SAVE_FLAGS.PNG_Z_DEFAULT_COMPRESSION); return(stream.ToArray()); } }
internal static void FreeImageResize(string path, int size, string outputDirectory) { using (var original = FreeImageBitmap.FromFile(path)) { var scaled = ScaledSize(original.Width, original.Height, size); var resized = new FreeImageBitmap(original, scaled.width, scaled.height); // JPEG_QUALITYGOOD is 75 JPEG. // JPEG_BASELINE strips metadata (EXIF, etc.) resized.Save(OutputPath(path, outputDirectory, FreeImage), FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD | FREE_IMAGE_SAVE_FLAGS.JPEG_BASELINE); } }
public void FreeImageResize(string input) { using (var original = FreeImageBitmap.FromFile(input)) { var scaled = ScaledSize(original.Width, original.Height, ThumbnailSize); var resized = new FreeImageBitmap(original, scaled.width, scaled.height); // JPEG_QUALITYGOOD is 75 JPEG. // JPEG_BASELINE strips metadata (EXIF, etc.) resized.Save(OutputPath(input, FreeImage), FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD | FREE_IMAGE_SAVE_FLAGS.JPEG_BASELINE); } }
/// <summary> /// Returns the Byte array from an image to be used in Taglib.Picture /// </summary> /// <param name="img"></param> /// <returns></returns> public static byte[] ImageToByte(Image img) { // Need to make a copy, otherwise we have a GDI+ Error byte[] byteArray = new byte[0]; using (MemoryStream stream = new MemoryStream()) { FreeImageBitmap bCopy = new FreeImageBitmap(img); bCopy.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYSUPERB); stream.Close(); byteArray = stream.ToArray(); } return(byteArray); }
/// <summary> /// Save a thumbnail file /// </summary> /// <param name="slide"></param> /// <param name="thumb"></param> private void saveThumbnail(String fileName, FreeImageBitmap thumb) { try { using (Stream stream = slideEditController.ResourceProvider.openWriteStream(fileName)) { thumb.Save(stream, FREE_IMAGE_FORMAT.FIF_PNG); } } catch (Exception ex) { Logging.Log.Error("{0} exception updating thumbnail. Message: {1}", ex.GetType().Name, ex.Message); } }
public static void Combine(ImageFile[] images, string outputFile, string mapFile) { // Find max width and total height var maxWidth = 0; var maxHeight = 0; var totalHeight = 0; foreach (var image in images) { totalHeight += image.Image.Height; if (image.Image.Width > maxWidth) maxWidth = image.Image.Width; if (image.Image.Height > maxHeight) maxHeight = image.Image.Height; } Console.WriteLine(string.Format("Number of images: {0}, total height: {1}px, width: {2}", images.Length, totalHeight, maxWidth)); // Create the actual sprite var currentY = 0; const int currentX = 0; var surface = new FreeImageBitmap(maxWidth, totalHeight); foreach (var image in images) { var freeImage = GetFreeImage(image); surface.Paste(freeImage, currentX, currentY, 0); currentY += image.Image.Height; image.X = currentX; image.Y = currentY; Console.WriteLine("{0} copied to {1}, {2}", image.Name, image.X, image.Y); } Console.WriteLine("Writing sprite: " + outputFile); using (var stream = File.OpenWrite(outputFile)) { surface.Save(stream, FREE_IMAGE_FORMAT.FIF_PNG); } Console.WriteLine("Writing sprite map: " + mapFile); using (var writer = File.CreateText(mapFile)) { foreach (var image in images) { writer.WriteLine(image); image.Dispose(); } } }
public void SaveImage(string destfilename) { if (isBitmap) { try { using (FreeImageBitmap temp = new FreeImageBitmap(resultbmp)) { temp.Save(destfilename); } } catch { } } }
static void Main(string[] args) { // string path = (@"E:\C\work\2019-07-00\贴图流程化测试\eeee.tga"); string path = args[0]; FreeImageBitmap ne = new FreeImageBitmap(path, FREE_IMAGE_FORMAT.FIF_TARGA); Size b = ne.Size; int image_h = b.Height; int image_w = b.Width; /// 这里抛出移除是因为会当做方块来循环, 应该是小 // FreeImageBitmap new_tem = new FreeImageBitmap(image_w, image_h); Bitmap new_tem = new Bitmap(image_w, image_h); Color tt = ne.GetPixel(0, 0); /// 优先获得高度 在高度上去处理 宽度 Console.WriteLine(image_w); Bitmap ne_type = (Bitmap)ne.ToBitmap(); ne.Dispose(); for (int i = 0; i < image_h; i++) { for (int j = 0; j < image_w; j++) { //Color t = ne.GetPixel(i, j); /// 优先获得高度 在高度上去处理 宽度 Color t = ne_type.GetPixel(j, i); Program pro = new Program(); Color srgbcolor = pro.linetosrgb(t); new_tem.SetPixel(j, i, srgbcolor); } } ///对图形处理完成 /// FreeImageBitmap yy = new FreeImageBitmap(new_tem); yy.Save(path); }
private void bSaveImage_Click(object sender, EventArgs e) { if (pictureBox.Image != null) { try { if (sfd.ShowDialog() == DialogResult.OK) { // Save the bitmap using autodetection using (FreeImageBitmap temp = new FreeImageBitmap(pictureBox.Image)) { temp.Save(sfd.FileName); } } } catch { } } }
private void ExportViaFreeImage(Metafile metafile, double width, double height) { Logger.Info("ExportViaFreeImage: Preset: {0}", Preset); Logger.Info("ExportViaFreeImage: Width: {0}; height: {1}", width, height); // Calculate the number of pixels needed for the requested // output size and resolution; size is given in points (1/72 in), // resolution is given in dpi. int px = (int)Math.Round(width / 72 * Preset.Dpi); int py = (int)Math.Round(height / 72 * Preset.Dpi); Logger.Info("ExportViaFreeImage: Pixels: x: {0}; y: {1}", px, py); Cancelling += Exporter_Cancelling; PercentCompleted = 10; _tiledBitmap = new TiledBitmap(px, py); FreeImageBitmap fib = _tiledBitmap.CreateFreeImageBitmap(metafile, EffectiveTransparency()); ConvertColor(fib); fib.SetResolution(Preset.Dpi, Preset.Dpi); fib.Comment = Versioning.SemanticVersion.Current.BrandName; PercentCompleted = 30; Logger.Info("ExportViaFreeImage: Saving {0} file", Preset.FileType); try { fib.Save( FileName, Preset.FileType.ToFreeImageFormat(), GetSaveFlags() ); } catch (Exception e) { Logger.Fatal("ExportViaFreeImage: FreeImageBitmap.Save() threw an exception!"); Logger.Fatal(e); throw; } finally { Cancelling -= Exporter_Cancelling; PercentCompleted = 50; } }
internal static void FreeImageResize(string path, int size, string outputDirectory) { using (var original = FreeImageBitmap.FromFile(path)) { int width, height; if (original.Width > original.Height) { width = size; height = original.Height * size / original.Width; } else { width = original.Width * size / original.Height; height = size; } var resized = new FreeImageBitmap(original, width, height); // JPEG_QUALITYGOOD is 75 JPEG. // JPEG_BASELINE strips metadata (EXIF, etc.) resized.Save(OutputPath(path, outputDirectory, FreeImage), FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD | FREE_IMAGE_SAVE_FLAGS.JPEG_BASELINE); } }
public static void Thumbnail(string path, string outpath) { const int size = 150; using (var original = FreeImageBitmap.FromFile(path)) { int width, height; if (original.Width > original.Height) { width = size; height = original.Height * size / original.Width; } else { width = original.Width * size / original.Height; height = size; } var resized = new FreeImageBitmap(original, width, height); // JPEG_QUALITYGOOD is 75 JPEG. // JPEG_BASELINE strips metadata (EXIF, etc.) //resized.Save() resized.Save(outpath); } }
public static Response GetPageImage(Guid id, int page, int width, int height, IResponseFormatter response) { // Restrict access to the FreeImage library to one thread at a time. lock (lockThis) { int max_width = 0; int max_height = 0; bool thumbnail = !(width == -1 && height == -1); bool processed = false; string filename = string.Format("{0}-p{1}-w{2}-h{3}.jpg", id, page, width, height); if (thumbnail) { MemoryStream cachestream = ImageCache.Instance.LoadFromCache(filename, true); // Cached thumbnails are assumed to be in the correct format and adhere to the size/format restrictions of the ipad. if (cachestream != null) { return(response.FromStream(cachestream, MimeTypes.GetMimeType(".jpg"))); } } else { // Check if a processed (rescaled and/or progressive) image is cached. string processed_filename = string.Format("{0}-p{1}-processed.jpg", id, page); MemoryStream cachestream = ImageCache.Instance.LoadFromCache(processed_filename, false); if (cachestream != null) { return(response.FromStream(cachestream, MimeTypes.GetMimeType(".jpg"))); } } MemoryStream stream = null; // Check if original image is in the cache. string org_filename = string.Format("{0}-p{1}.jpg", id, page); stream = ImageCache.Instance.LoadFromCache(org_filename, false); if (stream == null) { // Image is not in the cache, get it via ComicRack. var bytes = GetPageImageBytes(id, page); if (bytes == null) { return(HttpStatusCode.NotFound); } stream = new MemoryStream(bytes); // Always save the original page to the cache ImageCache.Instance.SaveToCache(org_filename, stream, false); } stream.Seek(0, SeekOrigin.Begin); #if USE_GDI Bitmap bitmap = new Bitmap(stream, false); int bitmap_width = (int)bitmap.Width; int bitmap_height = (int)bitmap.Height; #elif USE_DIB FIBITMAP dib = FreeImage.LoadFromStream(stream); if (dib == null) { Console.WriteLine("Loading bitmap failed. Aborting."); // Check whether there was an error message. return(HttpStatusCode.InternalServerError); } int bitmap_width = (int)FreeImage.GetWidth(dib); int bitmap_height = (int)FreeImage.GetHeight(dib); #elif USE_FIB FreeImageBitmap fib = FreeImageBitmap.FromStream(stream, false); if (fib == null) { Console.WriteLine("Loading bitmap failed. Aborting."); // Check whether there was an error message. return(HttpStatusCode.InternalServerError); } int bitmap_width = (int)fib.Width; int bitmap_height = (int)fib.Height; #endif if (ImageCache.Instance.use_max_dimension) { int mw, mh; if (bitmap_width >= bitmap_height) { mw = ImageCache.Instance.max_dimension_long; mh = ImageCache.Instance.max_dimension_short; } else { mw = ImageCache.Instance.max_dimension_short; mh = ImageCache.Instance.max_dimension_long; } if (bitmap_width > mw || bitmap_height > mh) { double scaleW = (double)mw / (double)bitmap_width; double scaleH = (double)mh / (double)bitmap_height; double scale = Math.Min(scaleW, scaleH); max_width = (int)Math.Floor(scale * bitmap_width); max_height = (int)Math.Floor(scale * bitmap_height); } else { max_width = bitmap_width; max_height = bitmap_height; } } else // Check if the image dimensions exceeds the maximum image dimensions if ((bitmap_width * bitmap_height) > ImageCache.Instance.maximum_imagesize) { max_width = (int)Math.Floor(Math.Sqrt((double)bitmap_width / (double)bitmap_height * (double)ImageCache.Instance.maximum_imagesize)); max_height = (int)Math.Floor((double)max_width * (double)bitmap_height / (double)bitmap_width); } else { max_width = bitmap_width; max_height = bitmap_height; } // Calculate the dimensions of the returned image. int result_width = width; int result_height = height; if (result_width == -1 && result_height == -1) { result_width = max_width; result_height = max_height; } else { if (result_width == -1) { result_height = Math.Min(max_height, result_height); double ratio = (double)result_height / (double)max_height; result_width = (int)Math.Floor(((double)max_width * ratio)); } else if (result_height == -1) { result_width = Math.Min(max_width, result_width); double ratio = (double)result_width / (double)max_width; result_height = (int)Math.Floor(((double)max_height * ratio)); } } // TODO: do this per requesting target device instead of using one global setting. // Resize ? if (result_width != bitmap_width || result_height != bitmap_height) { processed = true; #if USE_DIB || USE_FIB //FREE_IMAGE_FILTER resizer = FREE_IMAGE_FILTER.FILTER_BICUBIC; FREE_IMAGE_FILTER resizer = FREE_IMAGE_FILTER.FILTER_LANCZOS3; #if USE_FIB fib.Rescale(result_width, result_height, resizer); #else FIBITMAP newdib = FreeImage.Rescale(dib, result_width, result_height, resizer); if (!newdib.IsNull) { FreeImage.Unload(dib); dib.SetNull(); dib = newdib; } #endif #elif USE_GDI Bitmap resizedBitmap = Resize(bitmap, result_width, result_height); bitmap.Dispose(); bitmap = resizedBitmap; resizedBitmap = null; #endif } // Check if the image must be converted to progressive jpeg if (ImageCache.Instance.use_progressive_jpeg && (result_width * result_height) >= ImageCache.Instance.progressive_jpeg_size_threshold) { processed = true; // Convert image to progressive jpeg // FreeImage source code reveals that lower 7 bits of the FREE_IMAGE_SAVE_FLAGS enum are used for low-level quality control. FREE_IMAGE_SAVE_FLAGS quality = (FREE_IMAGE_SAVE_FLAGS)ImageCache.Instance.progressive_jpeg_quality; FREE_IMAGE_SAVE_FLAGS flags = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444 | FREE_IMAGE_SAVE_FLAGS.JPEG_PROGRESSIVE | quality; #if USE_DIB || USE_FIB stream.Dispose(); stream = new MemoryStream(); #if USE_FIB fib.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags); fib.Dispose(); #else FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags); FreeImage.Unload(dib); dib.SetNull(); #endif #else FIBITMAP dib = FreeImage.CreateFromBitmap(bitmap); bitmap.Dispose(); bitmap = null; stream.Dispose(); stream = new MemoryStream(); FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags); FreeImage.Unload(dib); dib.SetNull(); #endif } else if (processed) { // image was rescaled, make new stream with rescaled bitmap #if USE_DIB || USE_FIB FREE_IMAGE_SAVE_FLAGS flags = FREE_IMAGE_SAVE_FLAGS.JPEG_SUBSAMPLING_444 | FREE_IMAGE_SAVE_FLAGS.JPEG_OPTIMIZE | FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYNORMAL; stream.Dispose(); stream = new MemoryStream(); #if USE_FIB fib.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags); fib.Dispose(); #else FreeImage.SaveToStream(dib, stream, FREE_IMAGE_FORMAT.FIF_JPEG, flags); FreeImage.Unload(dib); dib.SetNull(); #endif #else stream = GetBytesFromImage(bitmap); #endif // For now, images that were resized because they exceeded the maximum dimensions are not saved to the cache. } #if USE_DIB FreeImage.Unload(dib); dib.SetNull(); #elif USE_FIB fib.Dispose(); #elif USE_GDI if (bitmap != null) { bitmap.Dispose(); bitmap = null; } #endif // Always save thumbnails to the cache if (thumbnail) { ImageCache.Instance.SaveToCache(filename, stream, true); } else if (processed) { // Store rescaled and/or progressive jpegs in the cache for now. string processed_filename = string.Format("{0}-p{1}-processed.jpg", id, page); ImageCache.Instance.SaveToCache(processed_filename, stream, false); } stream.Seek(0, SeekOrigin.Begin); return(response.FromStream(stream, MimeTypes.GetMimeType(".jpg"))); } }
protected void SavePBOhdr(string fileName) { OGLBuffer buffer = OutputBuffer as OGLBuffer; if (buffer == null) return; Vector4[] data = new Vector4[buffer.Width * buffer.Height]; buffer.GetDataNoAlloc<Vector4>(data); using (var bmp = new FreeImageBitmap(this.Width, this.Height, FREE_IMAGE_TYPE.FIT_RGBF)) { for (var j = 0ul; j < buffer.Height; j++) { var scanLine = bmp.GetScanline<FIRGBF>((int)buffer.Height - (int)j - 1); for (var i = 0ul; i < buffer.Width; i++) { var px = data[(int)i + (int)(buffer.Height - j - 1) * bmp.Width]; scanLine[(int)i] = new FIRGBF() { red = px.X, green = px.Y, blue = px.Z}; } } bmp.Save(fileName, FREE_IMAGE_FORMAT.FIF_EXR); } }
private bool MergeImages(string fileNameFormat, string outputDir, string prefix, int frameNum, string ext) { FreeImageBitmap combined = null; string fname = ""; bool supported = false; bool mergeSuccessful = true; FREE_IMAGE_TYPE type = FREE_IMAGE_TYPE.FIT_UNKNOWN; FreeImageBitmap source = null; string mergedFile = string.Format(fileNameFormat, outputDir, prefix, frameNum, ext); string tempFile = string.Format(fileNameFormat, outputDir, prefix, frameNum, "_tmp" + ext); // Allocate a bitmap to store the final image fname = string.Format(fileNameFormat, outputDir, "slice_0_" + prefix, frameNum, ext); try { source = new FreeImageBitmap(fname); if (source != null) { type = source.ImageType; switch (type) { case FREE_IMAGE_TYPE.FIT_BITMAP: if (source.ColorDepth == 32 || source.ColorDepth == 24) supported = true; break; case FREE_IMAGE_TYPE.FIT_RGB16: case FREE_IMAGE_TYPE.FIT_RGBA16: case FREE_IMAGE_TYPE.FIT_RGBAF: case FREE_IMAGE_TYPE.FIT_RGBF: supported = true; break; } } } catch (Exception ex) { logger.Error(ex, "Error opening slice file"); } if (supported == false) { Console.WriteLine("Image format not supported"); return false; } try { // Create a new image of the input file type and the correct size FIBITMAP newImage = FreeImage.AllocateT(type, Width, Height, source.ColorDepth, source.RedMask, source.BlueMask, source.GreenMask); FreeImage.SaveEx(newImage, tempFile); FreeImage.UnloadEx(ref newImage); source.Dispose(); source = null; GC.Collect(); GC.WaitForPendingFinalizers(); combined = new FreeImageBitmap(tempFile); } catch (Exception ex) { logger.Error(ex, "Error creating output file"); mergeSuccessful = false; } for (int i = 0; i < SlicesAcross * SlicesDown; i++) { // Load the image slice fname = string.Format(fileNameFormat, outputDir, "slice_" + i + "_" + prefix, frameNum, ext); FreeImageBitmap slice = new FreeImageBitmap(fname); int posX; int posY; if (SlicesDown > 1 && SlicesAcross > 1) { posX = i % SlicesAcross; posY = i / SlicesAcross; } else if (SlicesDown == 1) { posX = i; posY = 0; } else { posX = 0; posY = i; } // Calculate the image slice sizes and the row/column position double sizeV = (1.0 / SlicesDown) * Height; double sizeH = (1.0 / SlicesAcross) * Width; double overlapV = sizeV * (Overlap / 100.0); double overlapH = sizeH * (Overlap / 100.0); double realLeft = sizeH * posX; double left = realLeft - overlapH; double realTop = sizeV * posY; double top = realTop - overlapV; // Check the sizes are within limits and adjust left = Math.Max(0.0, left); top = Math.Max(0.0, top); try { switch (type) { case FREE_IMAGE_TYPE.FIT_BITMAP: if (slice.ColorDepth == 24) { for (int y = 0; y < slice.Height; y++) { int srcY = (slice.Height - 1) - y; int destY = (combined.Height - 1) - (srcY + (int)top); int topY = y + (int)top; Scanline<RGBTRIPLE> srcLine = (Scanline<RGBTRIPLE>)slice.GetScanline(y); Scanline<RGBTRIPLE> destLine = (Scanline<RGBTRIPLE>)combined.GetScanline(destY); for (int x = 0; x < slice.Width; x++) { int destX = x + (int)left; // Make sure it's not out of bounds if (destY >= Height || destY >= Width) continue; // Is the pixel in an overlapping Area if (topY < realTop || destX < realLeft) { MergePixel srcPixel = new MergePixel(srcLine[x].rgbtRed, srcLine[x].rgbtGreen, srcLine[x].rgbtBlue, 0); MergePixel destPixel = new MergePixel(destLine[destX].rgbtRed, destLine[destX].rgbtGreen, destLine[destX].rgbtBlue, 0); destPixel = CalculatePixelWeight(overlapV, overlapH, realLeft, left, realTop, top, y, topY, x, srcPixel, destPixel); RGBTRIPLE dest; dest.rgbtRed = destPixel.red > 255.0 ? (byte)255 : (byte)destPixel.red; dest.rgbtGreen = destPixel.green > 255.0 ? (byte)255 : (byte)destPixel.green; dest.rgbtBlue = destPixel.blue > 255.0 ? (byte)255 : (byte)destPixel.blue; destLine[destX] = dest; } else destLine[destX] = srcLine[x]; } } } else { for (int y = 0; y < slice.Height; y++) { int srcY = (slice.Height - 1) - y; int destY = (combined.Height - 1) - (srcY + (int)top); int topY = y + (int)top; Scanline<RGBQUAD> srcLine = (Scanline<RGBQUAD>)slice.GetScanline(y); Scanline<RGBQUAD> destLine = (Scanline<RGBQUAD>)combined.GetScanline(destY); for (int x = 0; x < slice.Width; x++) { int destX = x + (int)left; // Make sure it's not out of bounds if (destY >= Height || destY >= Width) continue; // Is the pixel in an overlapping Area if (topY < realTop || destX < realLeft) { MergePixel srcPixel = new MergePixel(srcLine[x].rgbRed, srcLine[x].rgbGreen, srcLine[x].rgbBlue, destLine[destX].rgbReserved); MergePixel destPixel = new MergePixel(destLine[destX].rgbRed, destLine[destX].rgbGreen, destLine[destX].rgbBlue, destLine[destX].rgbReserved); destPixel = CalculatePixelWeight(overlapV, overlapH, realLeft, left, realTop, top, y, topY, x, srcPixel, destPixel); RGBQUAD dest = new RGBQUAD(); dest.rgbRed = destPixel.red > 255.0 ? (byte)255 : (byte)destPixel.red; dest.rgbGreen = destPixel.green > 255.0 ? (byte)255 : (byte)destPixel.green; dest.rgbBlue = destPixel.blue > 255.0 ? (byte)255 : (byte)destPixel.blue; dest.rgbReserved = destPixel.alpha > 255.0 ? (byte)255 : (byte)destPixel.alpha; destLine[destX] = dest; } else destLine[destX] = srcLine[x]; } } } break; case FREE_IMAGE_TYPE.FIT_RGB16: for (int y = 0; y < slice.Height; y++) { int srcY = (slice.Height - 1) - y; int destY = (combined.Height - 1) - (srcY + (int)top); int topY = y + (int)top; Scanline<FIRGB16> srcLine = (Scanline<FIRGB16>)slice.GetScanline(y); Scanline<FIRGB16> destLine = (Scanline<FIRGB16>)combined.GetScanline(destY); for (int x = 0; x < slice.Width; x++) { int destX = x + (int)left; // Make sure it's not out of bounds if (destY >= Height || destY >= Width) continue; // Is the pixel in an overlapping Area if (topY < realTop || destX < realLeft) { MergePixel srcPixel = new MergePixel(srcLine[x].red, srcLine[x].green, srcLine[x].blue, 0); MergePixel destPixel = new MergePixel(destLine[destX].red, destLine[destX].green, destLine[destX].blue, 0); destPixel = CalculatePixelWeight(overlapV, overlapH, realLeft, left, realTop, top, y, topY, x, srcPixel, destPixel); FIRGB16 dest = new FIRGB16(); dest.red = (ushort)destPixel.red; dest.green = (ushort)destPixel.green; dest.blue = (ushort)destPixel.blue; destLine[destX] = dest; } else destLine[destX] = srcLine[x]; } } break; case FREE_IMAGE_TYPE.FIT_RGBA16: for (int y = 0; y < slice.Height; y++) { int srcY = (slice.Height - 1) - y; int destY = (combined.Height - 1) - (srcY + (int)top); int topY = y + (int)top; Scanline<FIRGBA16> srcLine = (Scanline<FIRGBA16>)slice.GetScanline(y); Scanline<FIRGBA16> destLine = (Scanline<FIRGBA16>)combined.GetScanline(destY); for (int x = 0; x < slice.Width; x++) { int destX = x + (int)left; // Make sure it's not out of bounds if (destY >= Height || destY >= Width) continue; // Is the pixel in an overlapping Area if (topY < realTop || destX < realLeft) { MergePixel srcPixel = new MergePixel(srcLine[x].red, srcLine[x].green, srcLine[x].blue, srcLine[x].alpha); MergePixel destPixel = new MergePixel(destLine[destX].red, destLine[destX].green, destLine[destX].blue, destLine[destX].alpha); destPixel = CalculatePixelWeight(overlapV, overlapH, realLeft, left, realTop, top, y, topY, x, srcPixel, destPixel); FIRGBA16 dest = new FIRGBA16(); dest.red = (ushort)destPixel.red; dest.green = (ushort)destPixel.green; dest.blue = (ushort)destPixel.blue; dest.alpha = (ushort)destPixel.alpha; destLine[destX] = dest; } else destLine[destX] = srcLine[x]; } } break; case FREE_IMAGE_TYPE.FIT_RGBAF: for (int y = 0; y < slice.Height; y++) { int srcY = (slice.Height - 1) - y; int destY = (combined.Height - 1) - (srcY + (int)top); int topY = y + (int)top; Scanline<FIRGBAF> srcLine = (Scanline<FIRGBAF>)slice.GetScanline(y); Scanline<FIRGBAF> destLine = (Scanline<FIRGBAF>)combined.GetScanline(destY); for (int x = 0; x < slice.Width; x++) { int destX = x + (int)left; // Make sure it's not out of bounds if (destY >= Height || destY >= Width) continue; // Is the pixel in an overlapping Area if (topY < realTop || destX < realLeft) { MergePixel srcPixel = new MergePixel(srcLine[x].red, srcLine[x].green, srcLine[x].blue, destLine[destX].alpha); MergePixel destPixel = new MergePixel(destLine[destX].red, destLine[destX].green, destLine[destX].blue, destLine[destX].alpha); destPixel = CalculatePixelWeight(overlapV, overlapH, realLeft, left, realTop, top, y, topY, x, srcPixel, destPixel); FIRGBAF dest = new FIRGBAF(); dest.red = (float)destPixel.red; dest.green = (float)destPixel.green; dest.blue = (float)destPixel.blue; dest.alpha = (float)destPixel.alpha; destLine[destX] = dest; } else destLine[destX] = srcLine[x]; } } break; case FREE_IMAGE_TYPE.FIT_RGBF: for (int y = 0; y < slice.Height; y++) { int srcY = (slice.Height - 1) - y; int destY = (combined.Height - 1) - (srcY + (int)top); int topY = y + (int)top; Scanline<FIRGBF> srcLine = (Scanline<FIRGBF>)slice.GetScanline(y); Scanline<FIRGBF> destLine = (Scanline<FIRGBF>)combined.GetScanline(destY); for (int x = 0; x < slice.Width; x++) { int destX = x + (int)left; // Make sure it's not out of bounds if (destY >= Height || destY >= Width) continue; // Is the pixel in an overlapping Area if (topY < realTop || destX < realLeft) { MergePixel srcPixel = new MergePixel(srcLine[x].red, srcLine[x].green, srcLine[x].blue, 0); MergePixel destPixel = new MergePixel(destLine[destX].red, destLine[destX].green, destLine[destX].blue, 0); destPixel = CalculatePixelWeight(overlapV, overlapH, realLeft, left, realTop, top, y, topY, x, srcPixel, destPixel); FIRGBF dest = new FIRGBF(); dest.red = (float)destPixel.red; dest.green = (float)destPixel.green; dest.blue = (float)destPixel.blue; destLine[destX] = dest; } else destLine[destX] = srcLine[x]; } } break; } slice.Dispose(); } catch (Exception ex) { logger.Error(ex, "Error merging image files"); mergeSuccessful = false; } } try { if (mergeSuccessful) { combined.Save(mergedFile); combined.Dispose(); combined = null; GC.Collect(); GC.WaitForPendingFinalizers(); File.Delete(tempFile); } else { Log += DateTime.Now.ToLongTimeString() + " Merging frame " + frameNum + " failed.\n"; } } catch (Exception ex) { logger.Error(ex, "Error writing combined file"); mergeSuccessful = false; } return mergeSuccessful; }
public void SaveAdd() { string filename = @"saveadd.tif"; FreeImageBitmap fib = new FreeImageBitmap(100, 100, PixelFormat.Format24bppRgb); try { fib.SaveAdd(); Assert.Fail(); } catch { } Assert.IsFalse(File.Exists(filename)); fib.Save(filename); fib.AdjustBrightness(0.3d); fib.SaveAdd(); FreeImageBitmap other = new FreeImageBitmap(100, 100, PixelFormat.Format24bppRgb); foreach (Scanline<RGBTRIPLE> scanline in other) { for (int i = 0; i < scanline.Length; i++) { scanline[i] = new RGBTRIPLE(Color.FromArgb(0x339955)); } } fib.SaveAdd(other); other.SaveAdd(filename); other.Dispose(); fib.Dispose(); fib = new FreeImageBitmap(filename); Assert.AreEqual(4, fib.FrameCount); fib.Dispose(); File.Delete(filename); Assert.IsFalse(File.Exists(filename)); }
public static void FreeImageSaveExrBitmap(string fileName, int width, int height, RgbSpectrum[] data, string[] watermark = null) { using (var bmp = new FreeImageBitmap(width, height, FREE_IMAGE_TYPE.FIT_RGBF)) { for (int i = 0; i < bmp.Height; i++) { Scanline<FIRGBF> s = bmp.GetScanline<FIRGBF>(i); for (int j = 0; j < bmp.Width; j++) { try { var spectra = data[j + i * bmp.Width]; s[j] = new FIRGBF() { blue = spectra.c3, green = spectra.c2, red = spectra.c1 }; } catch (Exception ex) { Console.WriteLine(ex.Message); } } } if (watermark != null) { ApplyWaterMark(10, 400, bmp.ToBitmap(), watermark); } bmp.Save(fileName, FREE_IMAGE_FORMAT.FIF_EXR, FREE_IMAGE_SAVE_FLAGS.EXR_NONE); bmp.TmoReinhard05(1, 0.4); bmp.Save(fileName, FREE_IMAGE_FORMAT.FIF_PNG); } }
public static void Create(DmiImage dmi, string path) { var builder = new StringBuilder("# BEGIN DMI\n"); builder.Append("version = 4.0\n"); builder.Append("\twidth = " + dmi.StateWidth + "\n"); builder.Append("\theight = " + dmi.StateHeight + "\n"); var totalImages = dmi.States.Sum(x => x.GetFrames().Sum(y => y.GetImages().Count)); var xY = Math.Min(10, totalImages); var totalWidth = (dmi.StateWidth * xY); var totalHeight = dmi.StateHeight * (int)Math.Ceiling(totalImages / (float)xY); int pixelX = 0; int pixelY = totalHeight - 1; var img = new FreeImageBitmap(totalWidth, totalHeight, PixelFormat.Format32bppPArgb); img.FillBackground(Color.FromArgb(0, 0, 0, 0)); foreach (var state in dmi.States) { builder.AppendFormat("state = \"{0}\"\n", state.Name); builder.AppendFormat("\tdirs = {0}\n", state.Dir); builder.AppendFormat("\tframes = {0}\n", state.Frames); if (state.HasDelay) builder.AppendFormat("\tdelay = {0}\n", state.GetDelayString); if (state.Rewind > 0) builder.AppendFormat("\trewind = {0}\n", state.Rewind); foreach (var frame in state.GetFrames()) { foreach (var image in frame.GetImages()) { for (int x = 0; x < dmi.StateWidth; x++) { for (int y = 0; y < dmi.StateHeight; y++) { img.SetPixel(pixelX + x, pixelY - y, image.Bitmap.GetPixel(x, y)); } } pixelX += dmi.StateWidth; if (pixelX >= totalWidth) { pixelY -= dmi.StateHeight; pixelX = 0; } } } } builder.AppendLine("# END DMI"); if (!Directory.Exists(Path.GetDirectoryName(path))) Directory.CreateDirectory(Path.GetDirectoryName(path)); img.Save(path, FREE_IMAGE_FORMAT.FIF_PNG, FREE_IMAGE_SAVE_FLAGS.PNG_Z_DEFAULT_COMPRESSION); // Work around because FREEIMAGE saves metatags as unicode. AddMetadata(path, "Description", builder.ToString()); }
// ================ Пробная программа - не используется ================== static void DocumentInputMain(string[] args) { string path = @"D:\Home\data\"; Console.WriteLine("Start DocumentInput"); //string fname = path + "WP_20170528_006.jpg"; string fname = path + "pharris1.tiff"; Stream stream = File.OpenRead(fname); //ExifInfo(stream); using (var original = FreeImageBitmap.FromStream(stream)) { Console.WriteLine($"Width={original.Width} Height={original.Height} ImageFormat={original.ImageFormat} {original.ToString()}"); foreach (var m in original.Metadata) { Console.WriteLine($"{m}"); } int x = original.Width, y = original.Height; double factor = 150.0 / (x > y ? (double)x : (double)y); int width = (int)(factor * x); int height = (int)(factor * y); var resized = new FreeImageBitmap(original, width, height); // JPEG_QUALITYGOOD is 75 JPEG. // JPEG_BASELINE strips metadata (EXIF, etc.) resized.Save(path + "out.jpg", FREE_IMAGE_FORMAT.FIF_JPEG, FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD | FREE_IMAGE_SAVE_FLAGS.JPEG_BASELINE); } //stream.Position = 0L; //Console.WriteLine($"ExifDate={ExifDate(stream)}"); //Console.WriteLine($"ExifDate={ExifDate(fname)}"); using (var image = new Bitmap(fname)) { Console.WriteLine($"Width={image.Width} Height={image.Height}"); foreach (var prop in image.PropertyItems) { Console.WriteLine($"{prop.Id} {prop.Len} {prop.Type} {prop.Value} "); } } string text = ""; // Используем пакет MesiaInfo.DotNetWrapper using (MediaInfo.DotNetWrapper.MediaInfo mediaInfo = new MediaInfo.DotNetWrapper.MediaInfo()) { text += "\r\n\r\nOpen\r\n"; mediaInfo.Open(fname); text += "\r\n\r\nInform with Complete=false\r\n"; mediaInfo.Option("Complete"); text += mediaInfo.Inform(); text += "\r\n\r\nInform with Complete=true\r\n"; mediaInfo.Option("Complete", "1"); text += mediaInfo.Inform(); text += "\r\n\r\nCustom Inform\r\n"; mediaInfo.Option("Inform", "General;File size is %FileSize% bytes"); text += mediaInfo.Inform(); //foreach (string param in new[] { "BitRate", "BitRate/String", "BitRate_Mode" }) //{ // text += "\r\n\r\nGet with Stream=Audio and Parameter='" + param + "'\r\n"; // text += mediaInfo.Get(StreamKind.Audio, 0, param); //} //text += "\r\n\r\nGet with Stream=General and Parameter=46\r\n"; //text += mediaInfo.Get(StreamKind.General, 0, 46); //text += "\r\n\r\nCount_Get with StreamKind=Stream_Audio\r\n"; //text += mediaInfo.CountGet(StreamKind.Audio); //text += "\r\n\r\nGet with Stream=General and Parameter='AudioCount'\r\n"; //text += mediaInfo.Get(StreamKind.General, 0, "AudioCount"); //text += "\r\n\r\nGet with Stream=Audio and Parameter='StreamCount'\r\n"; //text += mediaInfo.Get(StreamKind.Audio, 0, "StreamCount"); } Console.WriteLine(text); }
private void bSaveImage_Click(object sender, EventArgs e) { if (pictureBox.Image != null) { try { if (sfd.ShowDialog() == DialogResult.OK) { // Save the bitmap using autodetection using (FreeImageBitmap temp = new FreeImageBitmap(pictureBox.Image)) { temp.Save(sfd.FileName); } } } catch { } } }
public static void Create(DmiImage dmi, string path) { var builder = new StringBuilder("# BEGIN DMI\n"); builder.Append("version = 4.0\n"); builder.Append("\twidth = " + dmi.StateWidth + "\n"); builder.Append("\theight = " + dmi.StateHeight + "\n"); var totalImages = dmi.States.Sum(x => x.GetFrames().Sum(y => y.GetImages().Count)); var xY = Math.Min(10, totalImages); var totalWidth = (dmi.StateWidth * xY); var totalHeight = dmi.StateHeight * (int)Math.Ceiling(totalImages / (float)xY); int pixelX = 0; int pixelY = totalHeight - 1; var img = new FreeImageBitmap(totalWidth, totalHeight, PixelFormat.Format32bppPArgb); img.FillBackground(Color.FromArgb(0, 0, 0, 0)); foreach (var state in dmi.States) { builder.AppendFormat("state = \"{0}\"\n", state.Name); builder.AppendFormat("\tdirs = {0}\n", state.Dir); builder.AppendFormat("\tframes = {0}\n", state.Frames); if (state.HasDelay) { builder.AppendFormat("\tdelay = {0}\n", state.GetDelayString); } if (state.Rewind > 0) { builder.AppendFormat("\trewind = {0}\n", state.Rewind); } foreach (var frame in state.GetFrames()) { foreach (var image in frame.GetImages()) { for (int x = 0; x < dmi.StateWidth; x++) { for (int y = 0; y < dmi.StateHeight; y++) { img.SetPixel(pixelX + x, pixelY - y, image.Bitmap.GetPixel(x, y)); } } pixelX += dmi.StateWidth; if (pixelX >= totalWidth) { pixelY -= dmi.StateHeight; pixelX = 0; } } } } builder.AppendLine("# END DMI"); if (!Directory.Exists(Path.GetDirectoryName(path))) { Directory.CreateDirectory(Path.GetDirectoryName(path)); } img.Save(path, FREE_IMAGE_FORMAT.FIF_PNG, FREE_IMAGE_SAVE_FLAGS.PNG_Z_DEFAULT_COMPRESSION); // Work around because FREEIMAGE saves metatags as unicode. AddMetadata(path, "Description", builder.ToString()); }
/// <summary> /// Returns the Byte array from an image to be used in Taglib.Picture /// </summary> /// <param name="img"></param> /// <returns></returns> public static byte[] ImageToByte(Image img) { // Need to make a copy, otherwise we have a GDI+ Error byte[] byteArray = new byte[0]; using (MemoryStream stream = new MemoryStream()) { FreeImageBitmap bCopy = new FreeImageBitmap(img); bCopy.Save(stream, FREE_IMAGE_FORMAT.FIF_JPEG); stream.Close(); byteArray = stream.ToArray(); } return byteArray; }