/// <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); } }
private void breakUpImage(FreeImageBitmap image) { if (imageNeedsBreakup) { imageNeedsBreakup = false; foreach (var tile in tiles) { var tileImage = new FreeImageBitmap( (int)(image.Width * tile.Width), (int)(image.Height * tile.Height), FreeImageAPI.PixelFormat.Format32bppArgb); using (var destBox = tileImage.createPixelBox(PixelFormat.PF_A8R8G8B8)) { using (var sourceBox = image.createPixelBox()) { sourceBox.Left = (uint)(image.Width * tile.NodeLeft); sourceBox.Top = (uint)(image.Height * tile.NodeTop); sourceBox.Right = (uint)(sourceBox.Left + tileImage.Width); sourceBox.Bottom = (uint)(sourceBox.Top + tileImage.Height); PixelBox.BulkPixelConversion(sourceBox, destBox); } } //tileImage.saveToFile($"tilesdebug/{tile.NodeLeft}_{tile.NodeTop}.bmp", FREE_IMAGE_FORMAT.FIF_BMP); tile.Image = tileImage; } } }
//int imageId = 0; public void rescaleImage(FreeImageBitmap image, Size size, FREE_IMAGE_FILTER filter) { breakUpImage(image); //float wPercent = size.Width / (float)firstSeenImageSize.Width; //float hPercent = size.Height / (float)firstSeenImageSize.Height; //var newTileSize = new Size((int)(wPercent * originalTileSize.Width), (int)(hPercent * originalTileSize.Height)); image.Rescale(size, filter); //Need to resize the image, but will replace with individually sized tiles //image.saveToFile(imageId + "orig.bmp", FREE_IMAGE_FORMAT.FIF_BMP); using (var destBox = image.createPixelBox()) { foreach (var tile in tiles) { var newTileSize = new Size((int)(size.Width * tile.Width), (int)(size.Height * tile.Height)); tile.Image.Rescale(newTileSize, filter); using (var srcBox = tile.Image.createPixelBox(PixelFormat.PF_A8R8G8B8)) { var tx = size.Width * tile.NodeLeft; var ty = size.Height * tile.NodeTop; destBox.Left = (uint)tx; destBox.Top = (uint)ty; destBox.Right = (uint)(tx + newTileSize.Width); destBox.Bottom = (uint)(ty + newTileSize.Height); PixelBox.BulkPixelConversion(srcBox, destBox); //image.saveToFile("show/" + imageId++ + "tiled.bmp", FREE_IMAGE_FORMAT.FIF_BMP); } } } //image.saveToFile(imageId++ + "tiled.bmp", FREE_IMAGE_FORMAT.FIF_BMP); }
/// <summary> /// Load a FreeImage bitmap specifying different flags according to the file extension /// </summary> /// <param name="fileName"></param> /// <returns></returns> private FreeImageBitmap LoadBitmap(string fileName) { FREE_IMAGE_LOAD_FLAGS flags = FREE_IMAGE_LOAD_FLAGS.DEFAULT; // Rotate Jpegs if possible if (fileName.EndsWith("jpg", StringComparison.OrdinalIgnoreCase) || fileName.EndsWith("jpeg", StringComparison.OrdinalIgnoreCase)) { flags = FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE | FREE_IMAGE_LOAD_FLAGS.JPEG_EXIFROTATE; } // Load the image from disk try { var bmp = new FreeImageBitmap(fileName, flags); // Convert the image to bitmap if (bmp.ImageType != FREE_IMAGE_TYPE.FIT_BITMAP) { bmp.ConvertType(FREE_IMAGE_TYPE.FIT_BITMAP, true); } return(bmp); } catch { throw; // return null; } }
private void bLoadImage_Click(object sender, EventArgs e) { if (ofd.ShowDialog() == DialogResult.OK) { try { this.UseWaitCursor = true; // Load the file using autodetection FreeImageBitmap fib; fib = new FreeImageBitmap(ofd.FileName); // Rescale the image so that it fits the picturebox // Get the plugin that was used to load the bitmap FreeImagePlugin plug = PluginRepository.Plugin(fib.ImageFormat); lImageFormat.Text = String.Format("Format zdjęcia: {0}", plug.Format); // Replace the existing bitmap with the new one ReplaceBitmap(fib); HistGraph.Visible = true; bSaveImage.Enabled = true; bKriking.Enabled = true; this.UseWaitCursor = false; } catch { } } }
private Color GetAverageColor(FreeImageBitmap bmp) { if (bmp == null) { return(Color.Black); } if (bmp.Width < 2) { return(bmp.GetPixel(0, 0)); } var colors = new[] { bmp.GetPixel(0, 0), bmp.GetPixel(0, bmp.Height - 1), bmp.GetPixel(bmp.Width - 1, 0), bmp.GetPixel(bmp.Width - 1, bmp.Height - 1), bmp.GetPixel(bmp.Width / 2, 0), bmp.GetPixel(0, bmp.Height / 2), bmp.GetPixel(bmp.Width / 2, bmp.Height - 1), bmp.GetPixel(bmp.Width - 1, bmp.Height / 2), }; return(Color.FromArgb( (int)colors.Average(c => c.R), (int)colors.Average(c => c.G), (int)colors.Average(c => c.B) )); }
public DirectBitmap(Stream stream) { using (var srcBitmap = new FreeImageBitmap(stream)) { Width = srcBitmap.Width; Height = srcBitmap.Height; PixelBuffer = new byte[4 * Width * Height]; bitsHandle = GCHandle.Alloc(PixelBuffer, GCHandleType.Pinned); arrayPtr = bitsHandle.AddrOfPinnedObject(); int h = Height; int w = Width; unsafe { byte *dst = (byte *)arrayPtr.ToPointer(); byte *src1 = (byte *)srcBitmap.Bits.ToPointer() + srcBitmap.Pitch * (h - 1); for (int y = 0; y < h; y++) { if (y > 0) { src1 -= 2 * srcBitmap.Pitch - 1; } for (int x = 0; x < w; x++) { *dst++ = *src1++; *dst++ = *src1++; *dst++ = *src1++; *dst++ = 255; } } } } }
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"); } } }
protected MedicalState(LoadInfo info) { boneState = info.GetValue <AnimationManipulatorState>(BONE_MANIPULATOR_STATE); discState = info.GetValue <DiscState>(DISC_STATE); teethState = info.GetValue <TeethState>(TEETH_STATE); fossaState = info.GetValue <FossaState>(FOSSA_STATE); if (info.hasValue(NOTES)) { notes = info.GetValue <MedicalStateNotes>(NOTES); } else { notes = new MedicalStateNotes(); } if (info.hasValue(THUMBNAIL)) { using (MemoryStream memStream = new MemoryStream(info.GetBlob(THUMBNAIL))) { thumbnail = new FreeImageBitmap(memStream); memStream.Close(); } } else { thumbnail = null; } if (info.hasValue(NAME)) { Name = info.GetString(NAME); } else { Name = "Unnamed"; } }
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)); }
static Image LoadImageFI(FileStream fs) { Image img = null; try { // let's try FreeImage FreeImageBitmap fib = new FreeImageBitmap(fs); img = (Bitmap)fib; return img; } catch (Exception e) { if (e is DllNotFoundException) { // we can't reach the DLL, complain about that MessageBox.Show( // stack trace String.Format(Lightbox.Properties.Resources.DllNotFoundDescription, fs.Name, e.ToString()), Lightbox.Properties.Resources.DllNotFoundTitle + " - lightbox" ); return null; } else { // FI threw some other exception, so it can't load either return null; } } }
public void FreeImageResize() { using (var image = new FreeImageBitmap(Width, Height)) { image.Rescale(ResizedWidth, ResizedHeight, FREE_IMAGE_FILTER.FILTER_BICUBIC); } }
public static FreeImageBitmap LoadImage(Stream ajpStream) { MemoryStream jpegFile; MemoryStream pmsFile; AjpHeader ajpHeader; LoadImage(ajpStream, out jpegFile, out pmsFile, out ajpHeader); if (jpegFile == null) { return(null); } jpegFile.Position = 0; FreeImageBitmap jpegImage = new FreeImageBitmap(jpegFile, FREE_IMAGE_FORMAT.FIF_JPEG); jpegImage.Tag = ajpHeader; jpegImage.Comment = ajpHeader.GetComment(); if (pmsFile != null && pmsFile.Length > 0) { pmsFile.Position = 0; using (var pmsImage = Pms.LoadImage(pmsFile.ToArray())) { if (pmsImage == null) { return(jpegImage); } jpegImage.ConvertColorDepth(FREE_IMAGE_COLOR_DEPTH.FICD_32_BPP); jpegImage.SetChannel(pmsImage, FREE_IMAGE_COLOR_CHANNEL.FICC_ALPHA); } } return(jpegImage); }
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); }
public void makeSampleImage(FreeImageBitmap bitmap) { if (LoadLogo != null) { using (FreeImageBitmap logo = LoadLogo()) { float sizeRatio = (float)bitmap.Width / logo.Width; int finalLogoWidth = (int)(logo.Width * sizeRatio); int finalLogoHeight = (int)(logo.Height * sizeRatio); int currentY = 0; int imageHeight = bitmap.Height; bitmap.ConvertColorDepth(FREE_IMAGE_COLOR_DEPTH.FICD_24_BPP); logo.Rescale(finalLogoWidth, finalLogoHeight, FREE_IMAGE_FILTER.FILTER_BILINEAR); while (currentY < imageHeight) { int sectionHeight = logo.Height; if (currentY + sectionHeight > imageHeight) { sectionHeight = imageHeight - currentY; } using (FreeImageBitmap section = bitmap.Copy(0, currentY, logo.Width, currentY + sectionHeight)) { using (FreeImageBitmap logoComposite = logo.Copy(0, 0, logo.Width, sectionHeight)) { logoComposite.Composite(false, null, section); bitmap.Paste(logoComposite, 0, currentY, int.MaxValue); currentY += finalLogoHeight; } } } } } }
private void OpenFile(UniFile file) { m_file = file; try { if (file.FileExtension.ToLowerInvariant() == "dds") { m_image = new FreeImageBitmap(file.Stream, FREE_IMAGE_FORMAT.FIF_DDS); m_format = FREE_IMAGE_FORMAT.FIF_DDS; } else if (file.FileExtension.ToLowerInvariant() == "tga") { m_image = new FreeImageBitmap(file.Stream, FREE_IMAGE_FORMAT.FIF_TARGA); m_format = FREE_IMAGE_FORMAT.FIF_TARGA; } m_picbxImage.Image = (Bitmap)m_image; m_binary = new MemoryStream(); file.Stream.Position = 0; file.Stream.CopyTo(m_binary); } catch (Exception e) { UIHelper.ShowError("Failed to open image! Error: " + e.Message); ModTool.Core.LoggingManager.SendMessage("Failed to open image " + file.FilePath); ModTool.Core.LoggingManager.HandleException(e); } finally { file.Close(); } }
private FreeImageBitmap CreateFreeImageViaDIB() { FreeImageBitmap fi; using (DllManager dllManager = new DllManager()) { dllManager.LoadDll("FreeImage.DLL"); Logger.Info("CreateFreeImageViaDIB: Copy to clipboard and get data from it"); if (!CopySelection()) { return(null); } MemoryStream stream = Clipboard.GetData(System.Windows.DataFormats.Dib) as MemoryStream; using (DibBitmap dibBitmap = new DibBitmap(stream)) { Logger.Info("CreateFreeImageViaDIB: Create FreeImage bitmap"); fi = new FreeImageBitmap(dibBitmap.Bitmap); bool convertType = fi.ConvertType(FREE_IMAGE_TYPE.FIT_BITMAP, true); Logger.Debug("CreateFreeImageViaDIB: FreeImageBitmap.ConvertType returned {0}", convertType); bool convertColorDepth = fi.ConvertColorDepth(FREE_IMAGE_COLOR_DEPTH.FICD_24_BPP); // won't work with 32 bpp! Logger.Debug("CreateFreeImageViaDIB: FreeImageBitmap.ConvertColorDepth returned {0}", convertColorDepth); fi.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY); } } return(fi); }
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); }
/// <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); } }
private void compressCompositeNormalMap(String originalNormalMapSource, String source, String dest, MaterialDescription matDesc) { Task.WaitAll( saveUncompressed(source, dest, true, FREE_IMAGE_FILTER.FILTER_BILINEAR, new FullImageSizeStrategy(), (resized) => { String fileName = String.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(originalNormalMapSource), resized.Width, Path.GetExtension(originalNormalMapSource)); fileName = Path.Combine(Path.GetDirectoryName(originalNormalMapSource), fileName); if (File.Exists(fileName)) { Log.Info("Using manually supplied resized normal map for {0} size {1}", dest, resized.Width); using (var image = FreeImageBitmap.FromFile(fileName)) { if (image.Width != resized.Width || image.Height != resized.Height) { throw new Exception(String.Format("Image {0} does not match expected size {1}x{1}. Please fix source image.", fileName, resized.Width)); } combineImages(resized, Channel.Alpha, image, Channel.Red, image, Channel.Green, resized, Channel.Blue, resized); } } else { Log.Info("Using automatic resized normal map for {0} size {1}", dest, resized.Width); } }) ); }
private void checkImageDimensions(FreeImageBitmap image) { if (image.Width > pageWidth || image.Height > pageHeight) { throw new ImageAtlasException("The image is too large for the pages in this image atlas."); } }
public DmiImage(string file) { DmiName = Path.GetFileNameWithoutExtension(file); using (var stream = File.OpenRead(file)) { var imageData = new FreeImageBitmap(stream, FREE_IMAGE_FORMAT.FIF_PNG); var lines = new Queue <String>(imageData.Metadata.List[0].List[0].Value.ToString().Split('\n')); var start = lines.Dequeue(); if (start != "# BEGIN DMI") { throw new Exception("NOT DMI"); } ReadVersion(lines); while (lines.Count > 0) { var line = lines.Dequeue(); if (line == "# END DMI") { break; } if (line.StartsWith("state =")) { ReadState(GetValue(line), lines); } } _pixelY = 0; foreach (var state in States) { GetFrames(state, imageData); } } }
public DmiImage(string file) { DmiName = Path.GetFileNameWithoutExtension(file); using (var stream = File.OpenRead(file)) { var imageData = new FreeImageBitmap(stream); var lines = new Queue<String>(imageData.Metadata.List[0].List[0].Value.ToString().Split('\n')); var start = lines.Dequeue(); if (start != "# BEGIN DMI") throw new Exception("NOT DMI"); ReadVersion(lines); while (lines.Count > 0) { var line = lines.Dequeue(); if (line == "# END DMI") break; if (line.StartsWith("state =")) { ReadState(GetValue(line), lines); } } _pixelY = 0; foreach (var state in States) { GetFrames(state, imageData); } } }
public async Task <IActionResult> Create(CreateComponentTypeViewModel componentTypeViewModel) { if (ModelState.IsValid) { //Make image byte[] image; byte[] thumbnail; using (var m = new MemoryStream()) { await componentTypeViewModel.ImageUpload.CopyToAsync(m); image = m.ToArray(); } //Make thumbnail using (var m = new MemoryStream()) { await componentTypeViewModel.ImageUpload.CopyToAsync(m); using (var ti = new FreeImageBitmap(componentTypeViewModel.ImageUpload.OpenReadStream())) { var thumb = ti.GetThumbnailImage(100, true); using (var nm = new MemoryStream()) { thumb.Save(nm, Util.Util.FindImageFormat(componentTypeViewModel.ImageUpload.ContentType)); thumbnail = nm.ToArray(); } } } var componentType = new ComponentType { ComponentName = componentTypeViewModel.ComponentName, AdminComment = componentTypeViewModel.AdminComment, ComponentInfo = componentTypeViewModel.ComponentInfo, Datasheet = componentTypeViewModel.Datasheet, Location = componentTypeViewModel.Location, WikiLink = componentTypeViewModel.WikiLink, Manufacturer = componentTypeViewModel.Manufacturer, Image = new EsImage { ImageData = image, Thumbnail = thumbnail, ImageMimeType = componentTypeViewModel.ImageUpload.ContentType } }; var category = await _context.Categories.FirstOrDefaultAsync(c => c.CategoryId == componentTypeViewModel.Category); if (category != null) { _context.Add(componentType); await _context.SaveChangesAsync(); _context.Add(new ComponentTypeCategory { Category = category, ComponentType = componentType }); await _context.SaveChangesAsync(); } return(RedirectToAction(nameof(Index))); } return(View(componentTypeViewModel)); }
private unsafe void ResetRotateBitmap(FreeImageBitmap fib) { ((int *)fib.GetScanlinePointer(0))[0] = 0x00000001; ((int *)fib.GetScanlinePointer(0))[1] = 0x00000002; ((int *)fib.GetScanlinePointer(1))[0] = 0x00000003; ((int *)fib.GetScanlinePointer(1))[1] = 0x00000004; }
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)); } } }
private void ReplaceBitmap(FreeImageBitmap newBitmap) { // Checks whether the bitmap is usable if (newBitmap == null || newBitmap.IsDisposed) { MessageBox.Show("Unexpected error.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // Check whether the image type of the new bitmap is 'FIT_BITMAP'. // If not convert to 'FIT_BITMAP'. if (newBitmap.ImageType != FREE_IMAGE_TYPE.FIT_BITMAP) { if (!newBitmap.ConvertType(FREE_IMAGE_TYPE.FIT_BITMAP, true)) { MessageBox.Show("Error converting bitmap to standard type.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } if ((bitmap != null) && !object.ReferenceEquals(bitmap, newBitmap)) { bitmap.Dispose(); } if (resultbmp != null) { resultbmp.Dispose(); } bitmap = newBitmap; resultbmp = (Bitmap)bitmap; UpdateBitmapInformations(); }
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); } } }
private FreeImageBitmap CreateFreeImageViaDIB() { if (!CopySelection()) { return(null); } FreeImageBitmap fi; MemoryStream stream = null; Bovender.WpfHelpers.MainDispatcher.Invoke((Action)( () => { Logger.Info("CreateFreeImageViaDIB: Copy to clipboard and get data from it"); stream = Clipboard.GetData(System.Windows.DataFormats.Dib) as MemoryStream; }) ); using (DibBitmap dibBitmap = new DibBitmap(stream)) { Logger.Info("CreateFreeImageViaDIB: Create FreeImage bitmap"); fi = new FreeImageBitmap(dibBitmap.Bitmap); bool convertType = fi.ConvertType(FREE_IMAGE_TYPE.FIT_BITMAP, true); Logger.Debug("CreateFreeImageViaDIB: FreeImageBitmap.ConvertType returned {0}", convertType); bool convertColorDepth = fi.ConvertColorDepth(FREE_IMAGE_COLOR_DEPTH.FICD_24_BPP); // won't work with 32 bpp! Logger.Debug("CreateFreeImageViaDIB: FreeImageBitmap.ConvertColorDepth returned {0}", convertColorDepth); fi.RotateFlip(System.Drawing.RotateFlipType.RotateNoneFlipY); } stream.Dispose(); return(fi); }
public void Export(RadBitmap image, Stream stream) { Bitmap bitmap = image.ToBitmap(); FreeImageBitmap freeImageBitmap = new FreeImageBitmap(bitmap); freeImageBitmap.Save(stream, this.GetImageFormat()); }
private void GetFrames(DMIState state, FreeImageBitmap img) { for (int i = 0; i < state.Frames; i++) { int[] dirs = { Directions.SOUTH, Directions.NORTH, Directions.EAST, Directions.WEST, Directions.SOUTHEAST, Directions.SOUTHWEST, Directions.NORTHEAST, Directions.NORTHWEST }; var frame = new DMIFrame(state.GetDelay(i)); for (int j = 0; j < state.Dir; j++) { int dir = dirs[j]; if (_pixelX >= img.Width) { _pixelX = 0; _pixelY += StateHeight; } Bitmap frameBitmap; #if (ASEPRITE_LOAD) // string getString = "./in/FromAse/NabFinalParts/r_nabber" + state.colourStr + " (" + state.Name + ") " + Directions.DirToAse(dir) + ".png"; string getString = "./in/FromAse/NabFinalParts/r_nabber" + state.colourStr + " (" + state.Name + ") " + Directions.DirToAse(dir) + ".png"; FreeImageBitmap inImage = new FreeImageBitmap(getString); frameBitmap = inImage.ToBitmap(); #else frameBitmap = img.Copy(new Rectangle(_pixelX, _pixelY, StateWidth, StateHeight)).ToBitmap(); #endif frame.Add(new DMIImageData(frameBitmap, dir)); _pixelX += StateWidth; } state.Add(frame); } }
private static byte[] GetBGRFromBitmap(FreeImageBitmap bitmap, int w, int h) { byte[] pic = new byte[(w + 10) * (h + 10) * 3]; int o = 0; //get pic from bitmap for (int y = 0; y < h; y++) { var scanline = bitmap.GetScanlineFromTop8Bit(y); if (bitmap.ColorDepth == 24) { for (int x = 0; x < w; x++) { //get image data from RGB to BGR pic[o++] = scanline[x * 3 + 2]; pic[o++] = scanline[x * 3 + 1]; pic[o++] = scanline[x * 3 + 0]; } } else if (bitmap.ColorDepth == 32) { for (int x = 0; x < w; x++) { //get image data from RGB to BGR pic[o++] = scanline[x * 4 + 2]; pic[o++] = scanline[x * 4 + 1]; pic[o++] = scanline[x * 4 + 0]; } } } return(pic); }
public static void SaveToFile(FreeImageBitmap fib, string filepath, bool save_metadata) { if (!FreeImageIcsNativeMethods.SaveImage(fib.Dib, filepath, save_metadata)) { throw new FreeImageException("Unable to save file"); } }
public void Operators() { FreeImageBitmap fib1 = null, fib2 = null; Assert.IsTrue(fib1 == fib2); Assert.IsFalse(fib1 != fib2); Assert.IsTrue(fib1 == null); Assert.IsFalse(fib1 != null); fib1 = new FreeImageBitmap(10, 10, PixelFormat.Format24bppRgb); Assert.IsFalse(fib1 == fib2); Assert.IsTrue(fib1 != fib2); fib2 = fib1; fib1 = null; Assert.IsFalse(fib1 == fib2); Assert.IsTrue(fib1 != fib2); fib1 = new FreeImageBitmap(10, 9, PixelFormat.Format24bppRgb); Assert.IsFalse(fib1 == fib2); Assert.IsTrue(fib1 != fib2); fib2.Dispose(); fib2 = fib1; Assert.IsTrue(fib1 == fib2); Assert.IsFalse(fib1 != fib2); fib2 = fib1.Clone() as FreeImageBitmap; Assert.IsTrue(fib1 == fib2); Assert.IsFalse(fib1 != fib2); fib1.Dispose(); fib2.Dispose(); }
public static RgbSpectrumTexture FreeImageLoadBitmap(string fileName) { Console.WriteLine("..Loading ldr bitmap {0}", fileName); using (var bmp = new FreeImageBitmap(fileName)) { //bmp.AdjustGamma(2.2); var pdata = new RgbSpectrumInfo[bmp.Width * bmp.Height]; for (int i = 0; i < bmp.Height; i++) { if (bmp.ColorDepth == 24) { Scanline<RGBTRIPLE> s = bmp.GetScanline<RGBTRIPLE>(i); for (int j = 0; j < bmp.Width; j++) { pdata[j + i * bmp.Width] = RgbSpectrumInfo.Create(s[j].rgbtRed, s[j].rgbtGreen, s[j].rgbtBlue, false).Abs(); } } if (bmp.ColorDepth == 32) { Scanline<RGBQUAD> s = bmp.GetScanline<RGBQUAD>(i); for (int j = 0; j < bmp.Width; j++) { pdata[j + i * bmp.Width] = RgbSpectrumInfo.Create(s[j].rgbRed, s[j].rgbGreen, s[j].rgbBlue, false).Abs(); } } if (bmp.ColorDepth == 8) { Scanline<byte> s = bmp.GetScanline<byte>(i); for (int j = 0; j < bmp.Width; j++) { pdata[j + i * bmp.Width] = RgbSpectrumInfo.Create(bmp.Palette[s[j]].rgbRed, bmp.Palette[s[j]].rgbGreen, bmp.Palette[s[j]].rgbBlue, false).Abs(); } } } Console.WriteLine("... Converted size {0:F5} MBytes", (bmp.Width * bmp.Height * 12.0f) / (1024f * 1024f)); MemoryOccupied += (ulong)(bmp.Width * bmp.Height * 12u); var tex = new RgbSpectrumTexture(fileName, pdata, bmp.Width, bmp.Height); return tex; } }
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 Clone() { FreeImageBitmap fib = new FreeImageBitmap(iManager.GetBitmapPath(ImageType.Even, ImageColorType.Type_24)); object obj = new object(); fib.Tag = obj; FreeImageBitmap clone = fib.Clone() as FreeImageBitmap; Assert.IsNotNull(clone); Assert.AreEqual(fib.Width, clone.Width); Assert.AreEqual(fib.Height, clone.Height); Assert.AreEqual(fib.ColorDepth, clone.ColorDepth); Assert.AreSame(fib.Tag, clone.Tag); Assert.AreEqual(fib.ImageFormat, clone.ImageFormat); clone.Dispose(); fib.Dispose(); }
/// <summary> /// Create a Picture out of the given filename /// </summary> /// <param name="fileName"></param> public Picture(string fileName) { try { using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { FreeImageBitmap img = new FreeImageBitmap(fs); fs.Close(); Data = (Image)(img.Clone() as FreeImageBitmap); img.Dispose(); } } catch (Exception ex) { ServiceScope.Get<ILogger>().GetLogger.Error("Error creating picture from file: {0}. Error: {1}", fileName, ex.Message); } }
private void bNoise_Click(object sender, EventArgs e) { tempbitmap = mForm.smallbitmap; this.UseWaitCursor = true; for (int i = 0; i < smallbitmap.Width; i++) { for (int j = 0; j < smallbitmap.Height; j++) { if (smallbitmap.GetPixel(i, j).R > trackBarR.Value) mForm.smallbitmap.SetPixel(i, j, Color.Red); if (smallbitmap.GetPixel(i, j).G > trackBarG.Value) mForm.smallbitmap.SetPixel(i, j, Color.Red); if (smallbitmap.GetPixel(i, j).B > trackBarB.Value) mForm.smallbitmap.SetPixel(i, j, Color.Red); } } mForm.pictureBoxRefresh(); this.UseWaitCursor = false; mForm.smallbitmap = tempbitmap; }
public static RgbSpectrumTexture FreeImageLoadExrBitmap(string fileName) { Console.WriteLine("..Loading hdr bitmap {0}", fileName); using (var bmp = new FreeImageBitmap(fileName)) { //bmp.AdjustGamma(2.2); var pdata = new RgbSpectrumInfo[bmp.Width * bmp.Height]; for (int i = 0; i < bmp.Height; i++) { Scanline<FIRGBF> s = bmp.GetScanline<FIRGBF>(i); for (int j = 0; j < bmp.Width; j++) { pdata[j + i * bmp.Width] = new RgbSpectrumInfo(s[j].red, s[j].green, s[j].blue); //pdata[j + i * bmp.Width] .DeGamma(); } } Console.WriteLine("... Converted size {0:F5} MBytes", (bmp.Width * bmp.Height * 12.0f) / (1024f * 1024f)); MemoryOccupied += (ulong)(bmp.Width * bmp.Height * 12u); var tex = new RgbSpectrumTexture(fileName, pdata, bmp.Width, bmp.Height); return tex; } }
private void GetFrames(DMIState state, FreeImageBitmap img) { for (int i = 0; i < state.Frames; i++) { int[] dirs = { Directions.SOUTH, Directions.NORTH, Directions.EAST, Directions.WEST, Directions.SOUTHEAST, Directions.SOUTHWEST, Directions.NORTHEAST, Directions.NORTHWEST }; var frame = new DMIFrame(state.GetDelay(i)); for (int j = 0; j < state.Dir; j++) { int dir = dirs[j]; if (_pixelX >= img.Width) { _pixelX = 0; _pixelY += StateHeight; } Bitmap frameBitmap; frameBitmap = img.Copy(new Rectangle(_pixelX, _pixelY, StateWidth, StateHeight)).ToBitmap(); frame.Add(new DMIImageData(frameBitmap, dir)); _pixelX += StateWidth; } state.Add(frame); } }
private void bDarkFrame_Click(object sender, EventArgs e) { if (ofd.ShowDialog() == DialogResult.OK) { try { this.UseWaitCursor = true; FreeImageBitmap fib; // Load the file using autodetection fib = new FreeImageBitmap(ofd.FileName); // Rescale the image so that it fits the picturebox // Get the plugin that was used to load the bitmap FreeImagePlugin plug = PluginRepository.Plugin(fib.ImageFormat); // Replace the existing bitmap with the new one ReplaceBitmap(fib); bNoise.Enabled = true; bExecute.Enabled = true; this.UseWaitCursor = false; } catch { } } }
private unsafe void ResetRotateBitmap(FreeImageBitmap fib) { ((int*)fib.GetScanlinePointer(0))[0] = 0x00000001; ((int*)fib.GetScanlinePointer(0))[1] = 0x00000002; ((int*)fib.GetScanlinePointer(1))[0] = 0x00000003; ((int*)fib.GetScanlinePointer(1))[1] = 0x00000004; }
public void parse(FileStream source) { img = new FreeImageBitmap(source); dmi_width = img.Width; dmi_height = img.Height; MetadataModel model = img.Metadata.List[0]; string metaData = model.List[0].Value.ToString(); List<ImageInfoBlock> nodes = praseMetaData(metaData); String state_name = ""; List<int> state_delay = new List<int>(); int state_frames = 0; int state_directions = 0; Boolean had_state = false; this.states = new Dictionary<String, ImageState>(); // Enu<ImageInfoBlock> it = nodes.GetEnumerator(); for (int i = 0; i < nodes.Count; i++) { ImageInfoBlock block = nodes[i]; if (block.key == "dirs") { Int32.TryParse(block.value, out state_directions); } else if (block.key == "frames") { Int32.TryParse(block.value, out state_frames); } else if (block.key == "delay") { foreach(String S in block.value.Split(',')) { int x; Int32.TryParse(S, out x); state_delay.Add(x); } } else if (block.key == "version") { continue; } else if (block.key == "width") { Int32.TryParse(block.value, out width); } else if (block.key == "height") { Int32.TryParse(block.value, out height); } if (had_state) if(block.key == "state" || i == nodes.Count - 1) { if (state_frames == 0 || state_directions == 0) { throw new IOException(".DMI metadata malformed"); } if (state_delay.Count == 0) { while (state_delay.Count < state_frames) { state_delay.Add(1); } } if (state_delay.Count != state_frames) { throw new IOException(".DMI metadata malformed"); } ImageState state = generateSpriteState(state_frames, state_directions, state_delay); // intern state_name to make string comparison more efficient if(!states.ContainsKey(state_name)) states.Add(state_name, state); // add state to the sprite state_frames = 0; state_directions = 0; state_delay.Clear(); had_state = false; } if (block.key == "state") { state_name = block.value.Substring(1, block.value.Length - 2); had_state = true; } } }
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> /// Initializes a new instance of the <see cref="GifInformation"/> class /// with the specified <see cref="FreeImageBitmap"/>. /// </summary> /// <param name="bitmap">A reference to a <see cref="FreeImageBitmap"/> instance.</param> public GifInformation(FreeImageBitmap bitmap) : base(bitmap.Dib) { }
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); } }
/// <summary> /// Return an image from a given filename /// </summary> /// <param name = "fileName"></param> /// <param name = "size"></param> /// <returns></returns> private Image GetImageFromFile(string fileName, out Size size) { FreeImageBitmap img = null; size = new Size(0, 0); try { img = new FreeImageBitmap(fileName); size = img.Size; // convert Image Size to 64 x 64 for display in the Imagelist img.Rescale(64, 64, FREE_IMAGE_FILTER.FILTER_BOX); } catch (Exception ex) { log.Error("File has invalid Picture: {0} {1}", fileName, ex.Message); } return img != null ? (Image)img : null; }
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 { } } }
/// <summary> /// Creates an Image from a Taglib Byte structure /// </summary> /// <param name="data"></param> /// <returns></returns> public Image ImageFromData(byte[] data) { FreeImageBitmap img = null; try { MemoryStream ms = new MemoryStream(data); img = new FreeImageBitmap(ms); } catch (Exception) { } return img != null ? (Image)img : null; }
// Replaces the current bitmap with the given one. private void ReplaceBitmap(FreeImageBitmap newBitmap) { // Checks whether the bitmap is usable if (newBitmap == null || newBitmap.IsDisposed) { MessageBox.Show( "Unexpected error.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Check whether the image type of the new bitmap is 'FIT_BITMAP'. // If not convert to 'FIT_BITMAP'. if (newBitmap.ImageType != FREE_IMAGE_TYPE.FIT_BITMAP) { if (!newBitmap.ConvertType(FREE_IMAGE_TYPE.FIT_BITMAP, true)) { MessageBox.Show( "Error converting bitmap to standard type.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } // Dispose the old bitmap only in case it exists and // the old instance is another than the new one. if ((bitmap != null) && !object.ReferenceEquals(bitmap, newBitmap)) { bitmap.Dispose(); } // Dispose the picturebox's bitmap in case it exists. if (pictureBox.Image != null) { pictureBox.Image.Dispose(); } // Set the new bitmap. pictureBox.Image = bitmap = newBitmap; // Update gui. UpdateBitmapInformations(); UpdateFrameSelection(); }
// Replaces the current bitmap with the given one. private void ReplaceBitmap(FreeImageBitmap newBitmap) { // Checks whether the bitmap is usable if (newBitmap == null || newBitmap.IsDisposed) { MessageBox.Show( "Nispodziewany błąd.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } // Check whether the image type of the new bitmap is 'FIT_BITMAP'. // If not convert to 'FIT_BITMAP'. if (newBitmap.ImageType != FREE_IMAGE_TYPE.FIT_BITMAP) { if (!newBitmap.ConvertType(FREE_IMAGE_TYPE.FIT_BITMAP, true)) { MessageBox.Show( "Błąd konwersji bitmapy do standardowego typu.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } // Dispose the old bitmap only in case it exists and // the old instance is another than the new one. if ((bitmap != null) && !object.ReferenceEquals(bitmap, newBitmap)) { bitmap.Dispose(); } if ((smallbitmap != null) && !object.ReferenceEquals(smallbitmap, bitmap)) { smallbitmap.Dispose(); } bitmap = newBitmap; smallbitmap = bitmap; smallbitmap.Rescale(mForm.smallbitmap.Width, mForm.smallbitmap.Height, FREE_IMAGE_FILTER.FILTER_BICUBIC); UpdateBitmapInformations(); }
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)); }
/// <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; }
public bool PasteFromTopLeft(FreeImageBitmap src, Point location) { return FreeImage.PasteFromTopLeft(this.Dib, src.Dib, location.X, location.Y); }
private void bLoadImage_Click(object sender, EventArgs e) { if (ofd.ShowDialog() == DialogResult.OK) { try { // Load the file using autodetection FreeImageBitmap fib = new FreeImageBitmap(ofd.FileName); // Rescale the image so that it fits the picturebox // Get the plugin that was used to load the bitmap FreeImagePlugin plug = PluginRepository.Plugin(fib.ImageFormat); lImageFormat.Text = String.Format("Image-format: {0}", plug.Format); // Replace the existing bitmap with the new one ReplaceBitmap(fib); } catch { } } }
public bool PasteFromTopLeft(FreeImageBitmap src, int left, int top) { return FreeImage.PasteFromTopLeft(this.Dib, src.Dib, left, top); }
public void Resize(int width) { FreeImageBitmap bmp = new FreeImageBitmap(Data); int ratio = (int)((double)bmp.Height / bmp.Width * width); bmp.Rescale(width, ratio, FREE_IMAGE_FILTER.FILTER_BOX); Data = (Image) (bmp.Clone() as FreeImageBitmap); bmp.Dispose(); }