public void Example() { // Allocating a new bitmap with 99x99 pixels, 16-bit color depth and an allocation of 5 bits for each color. dib = FreeImage.Allocate(99, 99, 16, FreeImage.FI16_555_RED_MASK, FreeImage.FI16_555_GREEN_MASK, FreeImage.FI16_555_BLUE_MASK); // Saving bitmap. if (!FreeImage.SaveEx(ref dib, "example01.bmp", true)) { Console.WriteLine("Saving 'example.bmp' failed."); FreeImage.UnloadEx(ref dib); } // Allocation a new bitmap with 71x33 pixels, 4-bit color depth. Bitmaps below 16-bit have paletts. // Each pixel references an index within the palette wich contains the true color. // Therefor no bit-masks are needed and can be set to 0. dib = FreeImage.Allocate(71, 33, 4, 0, 0, 0); // Saving bitmap. if (!FreeImage.SaveEx(ref dib, "example02.tif", true)) { Console.WriteLine("Saving 'example02.tif' failed."); FreeImage.UnloadEx(ref dib); } // Allocation a new bitmap. This time 'AllocateT' is used because 'Allocate' can only create standard bitmaps. // In this case a RGBF bitmap is created. Red, green and blue are represented by a float-value so no bit-masks are needed. dib = FreeImage.AllocateT(FREE_IMAGE_TYPE.FIT_RGBF, 50, 75, 9, 0, 0, 0); // Saving bitmap. if (!FreeImage.SaveEx(ref dib, "example03.hdr", true)) { Console.WriteLine("Saving 'example03.hdr' failed."); FreeImage.UnloadEx(ref dib); } }
public List<MetaSimple> fiGetMetaData(FIBITMAP bm) { List<MetaSimple> results = new List<MetaSimple>(); // Create a wrapper for all metadata the image contains ImageMetadata iMetadata = new ImageMetadata(bm); // Get each metadata model foreach (MetadataModel metadataModel in iMetadata) { // Get each metadata tag and create a subnode for it foreach (MetadataTag metadataTag in metadataModel) { MetaSimple tagValue = new MetaSimple(); tagValue.ModelName = metadataModel.ToString(); tagValue.ModelTag = metadataTag.Key; tagValue.TagValue = metadataTag; results.Add(tagValue); } } return results; }
public byte[] Decode(PdfObject decodedObject, byte[] inputData, DecodeParameters decodeParameters) { FIBITMAP myImage = new FIBITMAP(); using (MemoryStream stream = new MemoryStream(inputData)) { myImage = FreeImage.LoadFromStream(stream); } Bitmap bitmap = FreeImage.GetBitmap(myImage); decodedObject.ColorSpace = ColorSpace.RGB; byte[] result = new byte[decodedObject.Width * decodedObject.Height * 3]; for (int i = 0; i < decodedObject.Width; i++) { for (int j = 0; j < decodedObject.Height; j++) { Color pixel = bitmap.GetPixel(i, j); int index = j * decodedObject.Width + i; result[index * 3] = pixel.R; result[index * 3 + 1] = pixel.G; result[index * 3 + 2] = pixel.B; } } return result; }
/// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="dib"/> is null.</exception> protected MetadataModel(FIBITMAP dib) { if (dib.IsNull) { throw new ArgumentNullException("dib"); } this.dib = dib; }
private void bLoad_Click(object sender, EventArgs e) { // Create variables OpenFileDialog ofd = new OpenFileDialog(); FIBITMAP dib = new FIBITMAP(); try { // Apply settings ofd.CheckFileExists = true; ofd.CheckPathExists = true; ofd.FileName = ""; ofd.Filter = "All files (*.*)|*.*"; ofd.Multiselect = false; ofd.RestoreDirectory = true; // Get image filename if (ofd.ShowDialog() == DialogResult.OK) { // Load the image dib = FreeImage.LoadEx(ofd.FileName); // Check if image was loaded successfully if (dib.IsNull) throw new Exception("Failed to load image."); // Clear the treeview tvMetadata.Nodes.Clear(); // Create a wrapper for all metadata the image contains ImageMetadata iMetadata = new ImageMetadata(dib); // Get each metadata model foreach (MetadataModel metadataModel in iMetadata) { // Create a new node for each model TreeNode modelNode = tvMetadata.Nodes.Add(metadataModel.ToString()); // Get each metadata tag and create a subnode for it foreach (MetadataTag metadataTag in metadataModel) { modelNode.Nodes.Add(metadataTag.Key + ": " + metadataTag.ToString()); } } } else { MessageBox.Show("Operation aborted.", "Aborted"); } } // Display error message catch (Exception ex) { while (ex.InnerException != null) ex = ex.InnerException; MessageBox.Show(ex.ToString(), "Exception caught"); } // Clean up finally { ofd.Dispose(); FreeImage.UnloadEx(ref dib); } }
public static void CleanUpResources(FIBITMAP dib) { // The bitmap was saved to disk but is still allocated in memory, so the handle has to be freed. if (!dib.IsNull) { FreeImage.Unload(dib); } // Make sure to set the handle to null so that it is clear that the handle is not pointing to a bitmap. dib = FIBITMAP.Zero; }
public void Example02() { dib = FreeImage.LoadEx("Sample.jpg", FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE); // Check whether loading succeeded if (dib.IsNull) { Console.WriteLine("Sample.jpg could not be loaded. Aborting."); return; } // Check whether the bitmap has 24 bpp color depth to ensure // using RGBTRIPPLE is correct. if (FreeImage.GetBPP(dib) != 24) { Console.WriteLine("Sample.jpg is no 24 bpp bitmap. Aborting."); FreeImage.UnloadEx(ref dib); return; } // Iterate over all scanlines for (int i = 0; i < FreeImage.GetHeight(dib); i++) { // Get scanline Scanline<RGBTRIPLE> scanline = new Scanline<RGBTRIPLE>(dib, i); // Get pixeldata from scanline RGBTRIPLE[] rgbt = scanline.Data; // Iterate over each pixel reducing the colors intensity to 3/4 which // will darken the bitmap. for (int j = 0; j < rgbt.Length; j++) { rgbt[j].rgbtBlue = (byte)((int)rgbt[j].rgbtBlue * 3 / 4); rgbt[j].rgbtGreen = (byte)((int)rgbt[j].rgbtGreen * 3 / 4); rgbt[j].rgbtRed = (byte)((int)rgbt[j].rgbtRed * 3 / 4); // In case no direct access to the data is implemented // the following way is equivalent: // // Color color = rgbt[j].color; // rgbt[j].color = Color.FromArgb(color.R * 3 / 4, color.G * 3 / 4, color.B * 3 / 4); } // Write the darkened scanline back to memory scanline.Data = rgbt; } // Store the bitmap to disk if (!FreeImage.SaveEx(ref dib, "SampleOut02.jpg", FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD, true)) { Console.WriteLine("Error while saving 'SampleOut02.jpg'"); FreeImage.UnloadEx(ref dib); } }
private void bLoadUrl_Click(object sender, EventArgs e) { // Verify url if (String.IsNullOrEmpty(tbURL.Text)) { MessageBox.Show("Please enter a valid URL.", "Error"); return; } FIBITMAP dib = new FIBITMAP(); Stream sourceStream = null; try { // Build a stream to read from WebRequest request = (WebRequest)HttpWebRequest.Create(tbURL.Text); WebResponse response = request.GetResponse(); sourceStream = response.GetResponseStream(); if (sourceStream == null) { throw new Exception(); } // Load the image from stream dib = FreeImage.LoadFromStream(sourceStream); // Check success if (dib.IsNull) { throw new Exception(); } // Convert the bitmap into a .NET bitmap Bitmap bitmap = FreeImage.GetBitmap(dib); if (bitmap == null) { throw new Exception(); } // Show the bitmap if (picBox.Image != null) { picBox.Image.Dispose(); } picBox.Image = bitmap; } catch { // Error handling MessageBox.Show("Error loading URL.", "Error"); } finally { // Clean up memory FreeImage.UnloadEx(ref dib); if (sourceStream != null) sourceStream.Dispose(); } }
public void Example01() { // Load sample file dib = FreeImage.LoadEx("Sample.jpg", FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE); // Check whether loading succeeded if (dib.IsNull) { Console.WriteLine("Sample.jpg could not be loaded. Aborting."); return; } // Check whether the bitmap has 24 bpp color depth to ensure // using RGBTRIPPLE is correct. if (FreeImage.GetBPP(dib) != 24) { Console.WriteLine("Sample.jpg is no 24 bpp bitmap. Aborting."); FreeImage.UnloadEx(ref dib); return; } // Store height of the bitmap int height = (int)FreeImage.GetHeight(dib); // Iterate over half of the bitmaps scanlines and swap // line[1] with line[height], line[2] with line[height-1] etc which will // flip the image. for (int i = 0; i < (height / 2); i++) { // Get scanline from the bottom part of the bitmap Scanline<RGBTRIPLE> scanlineBottom = new Scanline<RGBTRIPLE>(dib, i); // Get scanline from the top part of the bitmap Scanline<RGBTRIPLE> scanlineTop = new Scanline<RGBTRIPLE>(dib, height - 1 - i); // Get arrays of RGBTRIPPLEs that contain the bitmaps real pixel data // of the two scanlines. RGBTRIPLE[] rgbtBottom = scanlineBottom.Data; RGBTRIPLE[] rgbtTop = scanlineTop.Data; // Restore the scanline across to switch the bitmaps lines. scanlineBottom.Data = rgbtTop; scanlineTop.Data = rgbtBottom; } // Store the bitmap to disk if (!FreeImage.SaveEx(ref dib, "SampleOut01.jpg", FREE_IMAGE_SAVE_FLAGS.JPEG_QUALITYGOOD, true)) { Console.WriteLine("Error while saving 'SampleOut01.jpg'"); FreeImage.UnloadEx(ref dib); } }
/// <summary> /// Builds an FIBitmap from the stream and job.Settings /// </summary> /// <param name="s"></param> /// <param name="job"></param> /// <returns></returns> protected FIBITMAP buildFiBitmap(ref FIBITMAP original, ImageJob job, bool supportsTransparency, bool mayUnloadOriginal) { ResizeSettings settings = job.Settings; if (original.IsNull) return FIBITMAP.Zero; FIBITMAP final = FIBITMAP.Zero; //Find the image size Size orig = new Size((int)FreeImage.GetWidth(original), (int)FreeImage.GetHeight(original)); //Calculate the new size of the image and the canvas. ImageState state = new ImageState(settings, orig, true); c.CurrentImageBuilder.Process(state); RectangleF imageDest = PolygonMath.GetBoundingBox(state.layout["image"]); if (imageDest.Width != orig.Width || imageDest.Height != orig.Height) { //Rescale bool temp; final = FreeImage.Rescale(original, (int)imageDest.Width, (int)imageDest.Height, FreeImageScalingPlugin.ParseResizeAlgorithm(settings["fi.scale"], FREE_IMAGE_FILTER.FILTER_BOX, out temp)); if (mayUnloadOriginal) FreeImage.UnloadEx(ref original); if (final.IsNull) return FIBITMAP.Zero; } else { final = original; } RGBQUAD bgcolor = default(RGBQUAD); bgcolor.Color = settings.BackgroundColor; if (settings.BackgroundColor == Color.Transparent && !supportsTransparency) bgcolor.Color = Color.White; //If we need to leave padding, do so. BoxPadding outsideImage = new BoxPadding(imageDest.Left, imageDest.Top, state.destSize.Width - imageDest.Right, state.destSize.Height - imageDest.Bottom); if (outsideImage.All != 0) { var old = final; //Extend canvas final = FreeImage.EnlargeCanvas<RGBQUAD>(old, (int)outsideImage.Left, (int)outsideImage.Top, (int)outsideImage.Right, (int)outsideImage.Bottom, bgcolor.Color != Color.Transparent ? new Nullable<RGBQUAD>(bgcolor) : null, FREE_IMAGE_COLOR_OPTIONS.FICO_RGBA); if (old == original) { if (mayUnloadOriginal) { FreeImage.UnloadEx(ref original); old = original; } } else { FreeImage.UnloadEx(ref old); //'old' has the original value of 'final', which we allocated. } if (final.IsNull) return FIBITMAP.Zero; } return final; }
/// <summary> /// Creates a new ICC-Profile for <paramref name="dib"/>. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> /// <param name="data">The ICC-Profile data.</param> /// <param name="size">Number of bytes to use from data.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="dib"/> is null.</exception> public unsafe FIICCPROFILE(FIBITMAP dib, byte[] data, int size) { if (dib.IsNull) { throw new ArgumentNullException("dib"); } FIICCPROFILE prof; size = Math.Min(size, (int)data.Length); prof = *(FIICCPROFILE*)FreeImage.CreateICCProfile(dib, data, size); this.flags = prof.flags; this.size = prof.size; this.data = prof.data; }
public void Example01() { if (!File.Exists(fileName)) { Console.WriteLine(fileName + " does not exist. Aborting."); return; } // Try to unload the bitmap handle (in case it is not null). // Always assert that a handle (like dib) is unloaded before it is reused, because // on unmanaged side there is no garbage collector that will clean up unreferenced // objects. // The following code will produce a memory leak (in case the bitmap is loaded // successfully) because the handle to the first bitmap is lost: // dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_JPEG, fileName, FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE); // dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_JPEG, fileName, FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE); if (!dib.IsNull) FreeImage.Unload(dib); // Loading a sample bitmap. In this case it's a .jpg file. 'Load' requires the file // format or the loading process will fail. An additional flag (the default value is // 'DEFAULT') can be set to enable special loading options. dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_JPEG, fileName, FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE); // Check if the handle is null which means the bitmap could not be loaded. if (dib.IsNull) { Console.WriteLine("Loading bitmap failed. Aborting."); // Check whether there was an error message. return; } // Try flipping the bitmap. if (!FreeImage.FlipHorizontal(dib)) { Console.WriteLine("Unable to flip bitmap."); // Check whether there was an error message. } // Store the bitmap back to disk. Again the desired format is needed. In this case the format is 'TIFF'. // An output filename has to be chosen (which will be overwritten without a warning). // A flag can be provided to enable pluginfunctions (compression is this case). FreeImage.Save(FREE_IMAGE_FORMAT.FIF_TIFF, dib, outFileName, FREE_IMAGE_SAVE_FLAGS.TIFF_DEFLATE); // The bitmap was saved to disk but is still allocated in memory, so the handle has to be freed. if (!dib.IsNull) FreeImage.Unload(dib); // Make sure to set the handle to null so that it is clear that the handle is not pointing to a bitmap. dib.SetNull(); }
public FIBITMAP fiLoadImage(string fileName) { FIBITMAP bm = new FIBITMAP(); try { // Load the image bm = FreeImage.LoadEx(fileName); } catch (Exception) { throw new Exception("Failed to load image."); } return bm; }
public Base64Image(string dataURI, FREE_IMAGE_LOAD_FLAGS flags) { Match match = Regex.Match(dataURI, @"data:image/(?<type>.+?);base64,(?<data>.+)"); if (match.Groups["data"] != null) { byte[] byteArray = Convert.FromBase64String(match.Groups["data"].Value); using (MemoryStream byteStream = new MemoryStream(byteArray)) { dib.SetNull(); FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_PNG; if (match.Groups["type"] != null) { switch (match.Groups["type"].Value.ToLower()) { case "bmp": { format = FREE_IMAGE_FORMAT.FIF_BMP; break; } case "png": { format = FREE_IMAGE_FORMAT.FIF_PNG; break; } case "jpeg": case "jpg": { format = FREE_IMAGE_FORMAT.FIF_JPEG; break; } case "tga": { format = FREE_IMAGE_FORMAT.FIF_TARGA; break; } } } dib = FreeImage.LoadFromStream(byteStream, flags, ref format); } } }
/// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> public MDM_INTEROP(FIBITMAP dib) : base(dib) { }
public static extern FIBITMAP ColorQuantize(FIBITMAP dib, FreeImage.FreeImageQuantize quantize);
/// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> public MDM_EXIF_EXIF(FIBITMAP dib) : base(dib) { }
public static extern FIBITMAP RotateClassic(FIBITMAP dib, Double angle);
public static extern FIBITMAP Dither(FIBITMAP dib, FreeImage.FreeImageDither algorithm);
/// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> public MDM_XMP(FIBITMAP dib) : base(dib) { }
public static extern bool AdjustBrightness(FIBITMAP dib, Double percentage);
public static extern bool Paste(FIBITMAP dst, FIBITMAP src, int left, int top, int alpha);
public static extern FIBITMAP Clone(FIBITMAP dib);
public static extern bool SetChannel(FIBITMAP dib, FIBITMAP dib8, FreeImage.FreeImageColorChannel channel);
public static extern FIBITMAP Copy(FIBITMAP dib, int left, int top, int right, int bottom);
public static extern bool GetHistogram(FIBITMAP dib, int histo, FreeImage.FreeImageColorChannel channel);
public static extern bool Invert(FIBITMAP dib);
public static extern bool AdjustContrast(FIBITMAP dib, Double percentage);
/// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> public MDM_ANIMATION(FIBITMAP dib) : base(dib) { }
public static extern void Unload(FIBITMAP dib);
/// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> public MDM_MAKERNOTE(FIBITMAP dib) : base(dib) { }
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); }
/// <summary> /// Creates a new ICC-Profile for <paramref name="dib"/>. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> /// <param name="data">The ICC-Profile data.</param> /// <exception cref="ArgumentNullException"> /// <paramref name="dib"/> is null.</exception> public FIICCPROFILE(FIBITMAP dib, byte[] data) : this(dib, data, (int)data.Length) { }
/// <summary> /// Initializes a new instance based on the specified <see cref="FIBITMAP"/>, /// showing all known models. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> public ImageMetadata(FIBITMAP dib) : this(dib, false) { }
public static extern FIBITMAP RotateEx( FIBITMAP dib, Double angle, Double xShift, Double yShift, Double xOrigin, Double yOrigin, bool useMask);
/// <summary> /// Decodes the given stream, selects the correct page or frame, rotates it correctly (if autorotate=true), then executes the callback, then cleans up. /// </summary> /// <param name="s"></param> /// <param name="settings"></param> /// <param name="callback"></param> /// <returns></returns> public static object DecodeAndCall(Stream s, ResizeSettings settings, DecodeCallback callback) { if (!FreeImageAPI.FreeImage.IsAvailable()) { return(null); } FREE_IMAGE_LOAD_FLAGS flags = FREE_IMAGE_LOAD_FLAGS.DEFAULT; //If we're not tone-mapping the raw file, convert it for display if (!HasToneMappingCommands(settings)) { flags |= FREE_IMAGE_LOAD_FLAGS.RAW_DISPLAY; } bool usethumb = ("true".Equals(settings["usepreview"], StringComparison.OrdinalIgnoreCase)); if (usethumb) { flags |= FREE_IMAGE_LOAD_FLAGS.RAW_PREVIEW; } bool autorotate = ("true".Equals(settings["autorotate"], StringComparison.OrdinalIgnoreCase)); if (autorotate) { flags |= FREE_IMAGE_LOAD_FLAGS.JPEG_EXIFROTATE; } int page = 0; if (!string.IsNullOrEmpty(settings["page"]) && !int.TryParse(settings["page"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out page)) { page = 0; } int frame = 0; if (!string.IsNullOrEmpty(settings["frame"]) && !int.TryParse(settings["frame"], NumberStyles.Integer, NumberFormatInfo.InvariantInfo, out frame)) { frame = 0; } if (page == 0 && frame != 0) { page = frame; } Stopwatch sw = new Stopwatch(); sw.Start(); if (page > 1) { FREE_IMAGE_FORMAT fmt = FREE_IMAGE_FORMAT.FIF_UNKNOWN; FIMULTIBITMAP mb = FreeImage.OpenMultiBitmapFromStream(s, ref fmt, flags); //Prevent asking for a non-existent page int pages = FreeImage.GetPageCount(mb); if (page > pages) { page = pages; } try { if (mb.IsNull) { return(null); } FIBITMAP bPage = FreeImage.LockPage(mb, page - 1); if (bPage.IsNull) { return(null); } try { sw.Stop(); return(ToneMap(ref bPage, false, settings, callback)); } finally { FreeImage.UnlockPage(mb, bPage, false); } } finally { if (!mb.IsNull) { FreeImage.CloseMultiBitmapEx(ref mb, FREE_IMAGE_SAVE_FLAGS.DEFAULT); } } } else { FIBITMAP original = FIBITMAP.Zero; try { original = FreeImage.LoadFromStream(s, flags); sw.Stop(); if (original.IsNull) { return(null); } return(ToneMap(ref original, true, settings, callback)); } finally { if (!original.IsNull) { FreeImage.UnloadEx(ref original); } } } }
public static extern void ConvertToRawBits(IntPtr bits, FIBITMAP dib, int pitch, uint bpp, uint redMask, uint greenMask, uint blueMask, bool topDown);
public FreeImageAlgorithmsBitmap(FIBITMAP dib) : base(dib) { }
public static extern FIBITMAP Threshold(FIBITMAP dib, byte t);
public bool KernelCorrelateImageRegions(FreeImageAlgorithmsBitmap src2, FIARECT rect1, FIARECT rect2, FIBITMAP mask, CorrelationPrefilter prefilter, out FIAPOINT pt, out double max) { return FreeImage.KernelCorrelateImageRegions(this.Dib, rect1, src2.Dib, rect2, FIARECT.Empty, mask, prefilter, out pt, out max); }
public static extern FIBITMAP ConvertTo32Bits(FIBITMAP dib);
public bool KernelCorrelateImageRegions(FreeImageAlgorithmsBitmap src2, Rectangle rect1, Rectangle rect2, FIBITMAP mask, CorrelationPrefilter prefilter, out Point pt, out double max) { return this.KernelCorrelateImageRegions(src2, rect1, rect2, FIARECT.Empty, mask, prefilter, out pt, out max); }
/// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> public MDM_GEOTIFF(FIBITMAP dib) : base(dib) { }
public static extern bool IsTransparent(FIBITMAP dib);
/// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> public MDM_IPTC(FIBITMAP dib) : base(dib) { }
public static extern bool AdjustCurve(FIBITMAP dib, byte[] lut, FreeImage.FreeImageColorChannel channel);
/// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> public MDM_MAIN(FIBITMAP dib) : base(dib) { }
public static extern FIBITMAP Rescale(FIBITMAP dib, int dst_width, int dst_height, FreeImage.FreeImageFilter filter);
/// <summary> /// Initializes a new instance of this class. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> public MDM_NODATA(FIBITMAP dib) : base(dib) { }
public static extern bool FlipVertical(FIBITMAP dib);
public static extern FIBITMAP ConvertTo16Bits565(FIBITMAP dib);
public static extern bool FlipHorizontal(FIBITMAP dib);
/// <summary> /// Rescales the specified image. /// </summary> /// <remarks> /// The MipmapCount will be reset to 1 after this operation /// </remarks> /// <param name="image">The image.</param> /// <param name="libraryData">The library data.</param> /// <param name="rescale">The rescale.</param> private void Rescale(TexImage image, FreeImageTextureLibraryData libraryData, RescalingRequest rescale) { int width = rescale.ComputeWidth(image); int height = rescale.ComputeHeight(image); Log.Verbose("Rescaling image to " + width + "x" + height + " with " + rescale.Filter + " ..."); FIBITMAP[] newTab; if (image.Dimension == TexImage.TextureDimension.Texture3D) // in case of 3D Texture, we must rescale each slice of the top mipmap level { newTab = new FIBITMAP[image.ArraySize * image.FaceCount * image.Depth]; int curDepth; int nbSubImageWithMipMapPerArrayMemeber = 0; // calculating the number of sub images we have to jump to reach the next top level mipmap of the next array member curDepth = image.Depth; for (int i = 0; i < image.MipmapCount; ++i) { nbSubImageWithMipMapPerArrayMemeber += curDepth; curDepth = curDepth > 1 ? curDepth >>= 1 : curDepth; } int ct = 0; for (int j = 0; j < image.ArraySize; ++j) { for (int i = 0; i < image.Depth; ++i) { newTab[ct] = FreeImage.Rescale(libraryData.Bitmaps[i + j * nbSubImageWithMipMapPerArrayMemeber], width, height, (FREE_IMAGE_FILTER)rescale.Filter); ++ct; } } } else { newTab = new FIBITMAP[image.ArraySize]; int ct = 0; for (int i = 0; i < libraryData.Bitmaps.Length; i += image.MipmapCount) { newTab[ct] = FreeImage.Rescale(libraryData.Bitmaps[i], width, height, (FREE_IMAGE_FILTER)rescale.Filter); ++ct; } } for (int i = 0; i < libraryData.Bitmaps.Length; ++i) { FreeImage.Unload(libraryData.Bitmaps[i]); } libraryData.Bitmaps = newTab; image.Data = FreeImage.GetBits(newTab[0]); // Updating image data image.Rescale(width, height); int rowPitch, slicePitch; Tools.ComputePitch(image.Format, width, height, out rowPitch, out slicePitch); image.RowPitch = rowPitch; image.SlicePitch = slicePitch; image.MipmapCount = 1; image.DataSize = image.SlicePitch * image.ArraySize * image.FaceCount * image.Depth; }
public static extern bool AdjustGamma(FIBITMAP dib, Double gamma);
public static FIBITMAP EdgeDetect(FIBITMAP src) { return FreeImage.EdgeDetect(src); }
public static Bitmap Load(string path) { path = path.ToLower(); Bitmap bmp = null; //file *.hdr if (path.EndsWith(".hdr")) { FIBITMAP hdr = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_HDR, path, FREE_IMAGE_LOAD_FLAGS.RAW_DISPLAY); bmp = FreeImage.GetBitmap(FreeImage.ToneMapping(hdr, FREE_IMAGE_TMO.FITMO_DRAGO03, 2.2, 0)); FreeImage.Unload(hdr); } //file *.exr else if (path.EndsWith(".exr")) { FIBITMAP exr = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_EXR, path, FREE_IMAGE_LOAD_FLAGS.RAW_DISPLAY); bmp = FreeImage.GetBitmap(FreeImage.ToneMapping(exr, FREE_IMAGE_TMO.FITMO_DRAGO03, 2.2, 0)); FreeImage.Unload(exr); } //file *.svg else if (path.EndsWith(".svg")) { SvgDocument svg = SvgDocument.Open(path); bmp = svg.Draw(); } //TARGA file *.tga else if (path.EndsWith(".tga")) { using (Paloma.TargaImage tar = new Paloma.TargaImage(path)) { bmp = new Bitmap(tar.Image); } } //WEBP file *.webp else if (path.EndsWith(".webp")) { bmp = ReadWebpFile(path); } //PHOTOSHOP file *.PSD else if (path.EndsWith(".psd")) { System.Drawing.PSD.PsdFile psd = (new System.Drawing.PSD.PsdFile()).Load(path); bmp = System.Drawing.PSD.ImageDecoder.DecodeImage(psd); } else { using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read)) { bmp = new Bitmap(fs, true); //GIF file *.gif if (bmp.RawFormat.Equals(ImageFormat.Gif)) { bmp = new Bitmap(path); } //ICON file *.ico else if (bmp.RawFormat.Equals(ImageFormat.Icon)) { bmp = ReadIconFile(path); } else if (bmp.RawFormat.Equals(ImageFormat.Jpeg)) { //read Exif rotation int rotation = GetRotation(bmp); if (rotation != 0) { bmp = ScaleDownRotateBitmap(bmp, 1.0f, rotation); } } } } return(bmp); }
public bool KernelCorrelateImageRegions(FreeImageAlgorithmsBitmap src2, Rectangle rect1, Rectangle rect2, FIARECT searchRect, FIBITMAP mask, CorrelationPrefilter prefilter, out Point pt, out double max) { FIARECT fiaRect1 = new FIARECT(rect1); FIARECT fiaRect2 = new FIARECT(rect2); FIAPOINT fiaPoint = new FIAPOINT(); bool ret = FreeImage.KernelCorrelateImageRegions(this.Dib, fiaRect1, src2.Dib, fiaRect2, searchRect, mask, prefilter, out fiaPoint, out max); pt = new Point(fiaPoint.x, fiaPoint.y); return ret; }
/// <summary> /// Builds an FIBitmap from the stream and job.Settings /// </summary> /// <param name="s"></param> /// <param name="job"></param> /// <returns></returns> protected FIBITMAP buildFiBitmap(ref FIBITMAP original, ImageJob job, bool supportsTransparency, bool mayUnloadOriginal) { ResizeSettings settings = job.Settings; if (original.IsNull) { return(FIBITMAP.Zero); } FIBITMAP final = FIBITMAP.Zero; //Find the image size Size orig = new Size((int)FreeImage.GetWidth(original), (int)FreeImage.GetHeight(original)); //Calculate the new size of the image and the canvas. ImageState state = new ImageState(settings, orig, true); c.CurrentImageBuilder.Process(state); RectangleF imageDest = PolygonMath.GetBoundingBox(state.layout["image"]); if (imageDest.Width != orig.Width || imageDest.Height != orig.Height) { //Rescale bool temp; final = FreeImage.Rescale(original, (int)imageDest.Width, (int)imageDest.Height, FreeImageScalingPlugin.ParseResizeAlgorithm(settings["fi.scale"], FREE_IMAGE_FILTER.FILTER_BOX, out temp)); if (mayUnloadOriginal) { FreeImage.UnloadEx(ref original); } if (final.IsNull) { return(FIBITMAP.Zero); } } else { final = original; } RGBQUAD bgcolor = default(RGBQUAD); bgcolor.Color = settings.BackgroundColor; if (settings.BackgroundColor == Color.Transparent && !supportsTransparency) { bgcolor.Color = Color.White; } //If we need to leave padding, do so. BoxPadding outsideImage = new BoxPadding(imageDest.Left, imageDest.Top, state.destSize.Width - imageDest.Right, state.destSize.Height - imageDest.Bottom); if (outsideImage.All != 0) { var old = final; //Extend canvas final = FreeImage.EnlargeCanvas <RGBQUAD>(old, (int)outsideImage.Left, (int)outsideImage.Top, (int)outsideImage.Right, (int)outsideImage.Bottom, bgcolor.Color != Color.Transparent ? new Nullable <RGBQUAD>(bgcolor) : null, FREE_IMAGE_COLOR_OPTIONS.FICO_RGBA); if (old == original) { if (mayUnloadOriginal) { FreeImage.UnloadEx(ref original); old = original; } } else { FreeImage.UnloadEx(ref old); //'old' has the original value of 'final', which we allocated. } if (final.IsNull) { return(FIBITMAP.Zero); } } return(final); }
/// <summary> /// Resizes the given <paramref name="fullsizeImage"/> to a maximum <paramref name="maxWidth"/> and <paramref name="maxHeight"/> while preserving /// corrent aspect ratio. /// </summary> /// <param name="fullsizeImage">Image</param> /// <param name="maxWidth">Max. width</param> /// <param name="maxHeight">Max. height</param> /// <returns>Resized image</returns> public static FIBITMAP ResizeImage(FIBITMAP fullsizeImage, int maxWidth, int maxHeight) { int width = (int)FreeImage.GetWidth(fullsizeImage); int height = (int)FreeImage.GetHeight(fullsizeImage); if (width <= maxWidth && height <= maxHeight) return fullsizeImage; if (width <= maxWidth) maxWidth = width; int newHeight = height * maxWidth / width; if (newHeight > maxHeight) { // Resize with height instead maxWidth = width * maxHeight / height; newHeight = maxHeight; } FIBITMAP rescaled = FreeImage.Rescale(fullsizeImage, maxWidth, newHeight, FREE_IMAGE_FILTER.FILTER_LANCZOS3); FreeImage.UnloadEx(ref fullsizeImage); return rescaled; }
public static extern void SetTransparent(FIBITMAP dib, bool enabled);