public static unsafe IntPtr ConvertFromRawBits( byte[] bits, FREE_IMAGE_TYPE type, int width, int height, int pitch, uint bpp, uint red_mask, uint green_mask, uint blue_mask, bool topdown) { fixed(byte *ptr = bits) { return(ConvertFromRawBits( (IntPtr)ptr, type, width, height, pitch, bpp, red_mask, green_mask, blue_mask, topdown)); } }
/** * 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); }
/** * 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 int guessFibMaxValue(FreeImageAlgorithmsBitmap fib) { uint bpp = FreeImage.GetBPP(fib.Dib); FREE_IMAGE_TYPE type = FreeImage.GetImageType(fib.Dib); double min, max; if (bpp == 8) { return(256); } if (bpp >= 24 && type == FREE_IMAGE_TYPE.FIT_BITMAP) // colour image { return(256); } fib.FindMinMaxIntensity(out min, out max); if (max < 256) // 8 bit { return(256); } if (max < 4096) // 12 bit { return(4096); } if (max < 65536) // 16 bit { return(65536); } return(100000); // who knows! }
/// <summary> /// Expands images to have an alpha channel and swaps red and blue channels /// </summary> /// <param name="fBitmap">Image to process</param> /// <param name="imageType">Type of the image for the procedure</param> /// <returns></returns> private static FIBITMAP ConvertAndSwapChannels(FIBITMAP fBitmap, FREE_IMAGE_TYPE imageType) { FIBITMAP bgra; switch (imageType) { //Bitmap files are expanded to 32 bits before switching channels case FREE_IMAGE_TYPE.FIT_BITMAP: bgra = FreeImage.ConvertTo32Bits(fBitmap); FreeImage.UnloadEx(ref fBitmap); fBitmap = bgra; SwitchRedAndBlueChannels(fBitmap); break; //RGBF are switched before adding an alpha channel. case FREE_IMAGE_TYPE.FIT_RGBF: { // Swap R and B channels to make it BGR, then add an alpha channel SwitchRedAndBlueChannels(fBitmap); bgra = FreeImage.ConvertToType(fBitmap, FREE_IMAGE_TYPE.FIT_RGBAF, true); FreeImage.UnloadEx(ref fBitmap); fBitmap = bgra; } break; case FREE_IMAGE_TYPE.FIT_RGBAF: { // Swap R and B channels to make it BGRA SwitchRedAndBlueChannels(fBitmap); } break; } return(fBitmap); }
//GH 2016, need to update base_data when the Argo runs /** * Updates base_data with the corrected float arrays from the Argo Solution for each layer * @param image_name name of the .tiff file in Workspace corrected by Argo Solution * @param layer channel of the image that was corrected and is now updated * @return true if successfull **/ private bool updateBaseData(string image_name, int layer) { if (layer == -1) { return(false); } float[] pixel_data; FIBITMAP image = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_TIFF, image_name, FREE_IMAGE_LOAD_FLAGS.DEFAULT); FREE_IMAGE_TYPE type = FreeImage.GetImageType(image); uint width = FreeImage.GetWidth(image); uint height = FreeImage.GetHeight(image); uint pixels = width * height; float[] data = new float[width * height * base_dimensions[2]]; unsafe { pixel_data = new float[pixels]; for (int y = 0; y < height; ++y) { float *bits = (float *)FreeImage.GetScanLine(image, y); for (uint x = 0; x < width; ++x) { pixel_data[x + width * y] = bits[x]; } } } pixel_data.CopyTo(base_data, width * height * layer); return(true); }
public TileLoadInfo(int totalWidth, int totalHeight, int colorDepth, FREE_IMAGE_TYPE type, int pixelsPerMicron) { this.totalWidth = totalWidth; this.totalHeight = totalHeight; this.colorDepth = colorDepth; this.type = type; this.originalPixelsPerMicron = pixelsPerMicron; }
public TileLoadInfo(int totalWidth, int totalHeight, int colorDepth, FREE_IMAGE_TYPE type, int pixelsPerMicron) { this.totalWidth = totalWidth; this.totalHeight = totalHeight; this.colorDepth = colorDepth; this.type = type; this.originalPixelsPerMicron = pixelsPerMicron; }
public BitmapContent(int width, int height, ImageType imageType, byte[] data) { Width = width; Height = height; ImageType = imageType; int bpp; FREE_IMAGE_TYPE type = ImageTypeToFreeImageType(imageType, out bpp); _bitmap = FreeImage.ConvertFromRawBits(data, type, width, height, width * bpp, (uint)bpp, 0, 0, 0, false); }
internal Tile(string filepath, int number, Point position, int width, int height, int colorDepth, FREE_IMAGE_TYPE type) { this.dummyTile = false; this.number = number; this.originalPosition = position; this.ColorDepth = colorDepth; this.type = type; Initialise(filepath, width, height); }
internal Tile(Stream imageStream, string filepath, int number, Point position, int width, int height, int pixelFormat, int minIntensity, int maxIntensity, FREE_IMAGE_TYPE type) : this(filepath, number, position, width, height, pixelFormat, type) { FreeImageAlgorithmsBitmap fib = new FreeImageAlgorithmsBitmap(imageStream); this.thumbnail = fib; GC.KeepAlive(this.thumbnail); this.minIntensity = minIntensity; this.maxIntensity = maxIntensity; }
public FreeImageAlgorithmsBitmap(int width, int height, FREE_IMAGE_TYPE type, int colorDepth) { FIBITMAP dib = FreeImage.AllocateT(type, width, height, colorDepth, FreeImage.FI_RGBA_RED_MASK, FreeImage.FI_RGBA_GREEN_MASK, FreeImage.FI_RGBA_BLUE_MASK); if (dib.IsNull) { throw new Exception("Unable to create bitmap."); } this.ReplaceDib(dib); }
private void ImageViewerShown(object sender, EventArgs e) { Text = imageFile; Cursor.Current = Cursors.WaitCursor; ZoomLevels.SelectedIndexChanged -= ZoomLevelsSelectedIndexChanged; foreach (int zoom in ImageView.ZoomLevels) { ZoomLevels.Items.Add(string.Format("{0}%", zoom)); if (zoom == 100) { ZoomLevels.SelectedIndex = ZoomLevels.Items.Count - 1; } } ZoomLevels.SelectedIndexChanged += ZoomLevelsSelectedIndexChanged; try { originalImage = FreeImage.LoadEx(imageFile); if (!originalImage.IsNull) { Text = Text + " (" + FreeImage.GetHeight(originalImage) + " x " + FreeImage.GetWidth(originalImage) + ")"; FREE_IMAGE_TYPE type = FreeImage.GetImageType(originalImage); if (type != FREE_IMAGE_TYPE.FIT_BITMAP) { displayImage = FreeImage.ToneMapping(originalImage, FREE_IMAGE_TMO.FITMO_REINHARD05, 0, -1); } else { displayImage = FreeImage.Clone(originalImage); } if (!displayImage.IsNull) { ImageView.Image = FreeImage.GetBitmap(displayImage); icon = FreeImage.Rescale(displayImage, 16, 15, FREE_IMAGE_FILTER.FILTER_BOX); } } } catch (Exception ex) { Console.WriteLine("Error " + ex); } Cursor.Current = Cursors.Default; }
public static unsafe IntPtr ConvertFromRawBits( IntPtr bits, FREE_IMAGE_TYPE type, int width, int height, int pitch, uint bpp, uint red_mask, uint green_mask, uint blue_mask, bool topdown) { byte *addr = (byte *)bits; if ((addr == null) || (width <= 0) || (height <= 0)) { return(IntPtr.Zero); } IntPtr dib = AllocateT(type, width, height, (int)bpp, red_mask, green_mask, blue_mask); if (dib != IntPtr.Zero) { if (topdown) { for (int i = height - 1; i >= 0; --i) { CopyMemory((byte *)GetScanLine(dib, i), addr, (int)GetLine(dib)); addr += pitch; } } else { for (int i = 0; i < height; ++i) { CopyMemory((byte *)GetScanLine(dib, i), addr, (int)GetLine(dib)); addr += pitch; } } } return(dib); }
/// <summary> /// Expands images to have an alpha channel and swaps red and blue channels /// </summary> /// <param name="fBitmap">Image to process</param> /// <param name="imageType">Type of the image for the procedure</param> /// <returns></returns> private static FIBITMAP ConvertAndSwapChannels(FIBITMAP fBitmap, FREE_IMAGE_TYPE imageType) { FIBITMAP bgra; switch (imageType) { // Return BGRA images as is case FREE_IMAGE_TYPE.FIT_RGBAF: case FREE_IMAGE_TYPE.FIT_RGBA16: break; // Add an alpha channel to BGRA images without one case FREE_IMAGE_TYPE.FIT_RGBF: bgra = FreeImage.ConvertToType(fBitmap, FREE_IMAGE_TYPE.FIT_RGBAF, true); FreeImage.UnloadEx(ref fBitmap); fBitmap = bgra; break; case FREE_IMAGE_TYPE.FIT_RGB16: bgra = FreeImage.ConvertToType(fBitmap, FREE_IMAGE_TYPE.FIT_RGBA16, true); FreeImage.UnloadEx(ref fBitmap); fBitmap = bgra; break; // Add an alpha channel to RGB images // Swap the red and blue channels of RGBA images default: // Bitmap and other formats are converted to 32-bit by default bgra = FreeImage.ConvertTo32Bits(fBitmap); SwitchRedAndBlueChannels(bgra); FreeImage.UnloadEx(ref fBitmap); fBitmap = bgra; break; } return(fBitmap); }
/// <summary> /// Expands images to have an alpha channel and swaps red and blue channels /// </summary> /// <param name="fBitmap">Image to process</param> /// <param name="imageType">Type of the image for the procedure</param> /// <returns></returns> private static FIBITMAP ConvertAndSwapChannels(FIBITMAP fBitmap, FREE_IMAGE_TYPE imageType) { FIBITMAP bgra; switch (imageType) { // RGBF are switched before adding an alpha channel. case FREE_IMAGE_TYPE.FIT_RGBF: // Swap R and B channels to make it BGR, then add an alpha channel SwitchRedAndBlueChannels(fBitmap); bgra = FreeImage.ConvertToType(fBitmap, FREE_IMAGE_TYPE.FIT_RGBAF, true); FreeImage.UnloadEx(ref fBitmap); fBitmap = bgra; break; case FREE_IMAGE_TYPE.FIT_RGB16: // Swap R and B channels to make it BGR, then add an alpha channel SwitchRedAndBlueChannels(fBitmap); bgra = FreeImage.ConvertToType(fBitmap, FREE_IMAGE_TYPE.FIT_RGBA16, true); FreeImage.UnloadEx(ref fBitmap); fBitmap = bgra; break; case FREE_IMAGE_TYPE.FIT_RGBAF: case FREE_IMAGE_TYPE.FIT_RGBA16: // Swap R and B channels to make it BGRA SwitchRedAndBlueChannels(fBitmap); break; default: // Bitmap and other formats are converted to 32-bit by default bgra = FreeImage.ConvertTo32Bits(fBitmap); SwitchRedAndBlueChannels(bgra); FreeImage.UnloadEx(ref fBitmap); fBitmap = bgra; break; } return(fBitmap); }
public void ConvertBitmap(ImageType newImageType) { if (ImageType == newImageType) { return; } int newbpp, oldbpp; FREE_IMAGE_TYPE newType = ImageTypeToFreeImageType(newImageType, out newbpp); FREE_IMAGE_TYPE oldType = ImageTypeToFreeImageType(ImageType, out oldbpp); if (newType != oldType || newbpp != oldbpp) { FIBITMAP newBitmap = FreeImage.ConvertToType(_bitmap, newType, false); FreeImage.UnloadEx(ref _bitmap); _bitmap = newBitmap; } // check if a change in color space is needed. if (IsGammaCorrected(ImageType) != IsGammaCorrected(newImageType)) { double gamma; if (IsGammaCorrected(ImageType)) // from linear color space to non linear { gamma = 1d / 2.2d; } else { gamma = 2.2d; } if (!FreeImage.AdjustGamma(_bitmap, gamma)) { throw new ContentLoadException("FreeImage was unable to adjust the bitmap's gamma"); } } ImageType = newImageType; }
public static extern FIBITMAP ConvertToType(FIBITMAP dib, FREE_IMAGE_TYPE dst_type, bool scale_linear);
public static extern bool FIFSupportsICCProfiles(FREE_IMAGE_FORMAT format, FREE_IMAGE_TYPE ftype);
public static extern bool FIFSupportsExportType(FREE_IMAGE_FORMAT format, FREE_IMAGE_TYPE ftype);
public static extern uint ConvertToType(uint dib, FREE_IMAGE_TYPE dst_type, bool scale_linear);
// This plugin can only export standard bitmaps protected override bool SupportsExportTypeProc(FREE_IMAGE_TYPE type) { return (type == FREE_IMAGE_TYPE.FIT_BITMAP); }
private void SaveHelper(TextureFormat format, byte[] rawBytes, int texwidth, int texheight, bool convertTo16, ChannelsPerMap exportChannels, string imagePath, FREE_IMAGE_FORMAT destFormat, FREE_IMAGE_SAVE_FLAGS saveFlags) { int bytesPerPixel = 4; FREE_IMAGE_TYPE imageType = FREE_IMAGE_TYPE.FIT_BITMAP; switch (format) { case TextureFormat.RGBAHalf: imageType = FREE_IMAGE_TYPE.FIT_RGBA16; bytesPerPixel = 8; break; case TextureFormat.RGBAFloat: imageType = FREE_IMAGE_TYPE.FIT_RGBAF; bytesPerPixel = 16; break; case TextureFormat.ARGB32: imageType = FREE_IMAGE_TYPE.FIT_BITMAP; bytesPerPixel = 4; //tex.GetPixels32(); //ConvertBGRAtoARGBScanline(dib); // convert back to ARGB if (FreeImage.IsLittleEndian()) { for (int j = 0; j < rawBytes.Length; j += 4) { // convert BGRA to ARGB var a = rawBytes[j]; var r = rawBytes[j + 1]; rawBytes[j] = rawBytes[j + 3]; rawBytes[j + 1] = rawBytes[j + 2]; rawBytes[j + 2] = r; rawBytes[j + 3] = a; } } break; case TextureFormat.RGB24: imageType = FREE_IMAGE_TYPE.FIT_BITMAP; bytesPerPixel = 3; if (FreeImage.IsLittleEndian()) { // convert back to RGB for (int i = 0; i < rawBytes.Length; i += 3) { // convert BGR to RGB var r = rawBytes[i]; rawBytes[i] = rawBytes[i + 2]; rawBytes[i + 2] = r; } } break; } FIBITMAP dib = FreeImage.ConvertFromRawBits(rawBytes, imageType, texwidth, texheight, texwidth * bytesPerPixel, (uint)bytesPerPixel * 8, 0, 0, 0, false); if (dib.IsNull) { Debug.LogError("Dib is NULL!!!"); } rawBytes = null; GC.Collect(); if (convertTo16) { dib = FreeImage.ConvertToType(dib, FREE_IMAGE_TYPE.FIT_RGBA16, false); format = TextureFormat.RGBAHalf; } switch (exportChannels) { case ChannelsPerMap.RGB: // remove alpha channel switch (format) { case TextureFormat.RGBAFloat: dib = FreeImage.ConvertToRGBF(dib); break; case TextureFormat.RGBAHalf: dib = FreeImage.ConvertToType(dib, FREE_IMAGE_TYPE.FIT_RGB16, false); break; case TextureFormat.ARGB32: dib = FreeImage.ConvertTo24Bits(dib); break; } break; case ChannelsPerMap.R: dib = FreeImage.GetChannel(dib, FREE_IMAGE_COLOR_CHANNEL.FICC_RED); break; // if already RGBA don't need to do any conversion default: break; } try { using (FileStream saveStream = new FileStream(imagePath, FileMode.OpenOrCreate, FileAccess.Write)) { Debug.Log("FreeImage::FileSaveSuccess: " + imagePath + " :" + FreeImage.SaveToStream(ref dib, saveStream, destFormat, saveFlags, true)); } } catch (Exception e) { Debug.LogException(e); //progressBar.DoneProgress(); FreeImage.UnloadEx(ref dib); throw; } //if (progressBar != null) //{ // UnityThreadHelper.Dispatcher.Dispatch(() => // { // progressBar.Increment(); // }); //} }
/// <summary> /// Function that can be implemented. /// </summary> protected virtual bool SupportsExportTypeProc(FREE_IMAGE_TYPE type) { return(false); }
public static extern FIBITMAP AllocateT(FREE_IMAGE_TYPE type, int width, int height, int bpp, uint red_mask, uint green_mask, uint blue_mask);
internal static extern FIBITMAP AllocateExT(FREE_IMAGE_TYPE type, int width, int height, int bpp, IntPtr color, FREE_IMAGE_COLOR_OPTIONS options, RGBQUAD[] palette, uint red_mask, uint green_mask, uint blue_mask);
/// <summary> /// Function that can be implemented. /// </summary> protected virtual bool SupportsExportTypeProc(FREE_IMAGE_TYPE type) { return false; }
public void ConvertToType(FREE_IMAGE_TYPE type) { FIBITMAP tmp_dib = FreeImage.ConvertToType(this.Dib, type, true); this.ReplaceDib(tmp_dib); }
public static extern FIBITMAP ConvertToStandardType(FIBITMAP dib, FREE_IMAGE_TYPE dst_type, bool scale_linear);
public static extern IntPtr AllocateT(FREE_IMAGE_TYPE type, int width, int height, int bpp, uint red_mask, uint green_mask, uint blue_mask);
public static extern IntPtr ConvertToType(IntPtr src, FREE_IMAGE_TYPE dst_type, bool scale_linear);
public static extern FIBITMAP ConvertToType(FIBITMAP src, FREE_IMAGE_TYPE dst_type, bool scale_linear);
internal static extern FIBITMAP StretchImageToType(FIBITMAP src, FREE_IMAGE_TYPE type, double max);
/// <summary> /// Checks whether this plugin can save a bitmap in the desired data type. /// </summary> /// <param name="type">The desired image type.</param> /// <returns>True if this plugin can save bitmaps as the desired type, else false.</returns> public bool SupportsExportType(FREE_IMAGE_TYPE type) { return(FreeImage.FIFSupportsExportType(fif, type)); }
public RenderTexture LoadImage(string path, bool isLinear = false, bool isGrayscale = false, bool doMipMaps = false, bool forceGC = false, bool premultiplyAlpha = false) { // default bits per channel //uint origBPP = outBPP = 0; bool successfullyLoadedRaw = false; int width = 0, height = 0; TextureFormat formatToLoad = TextureFormat.ARGB32; RenderTextureFormat rtFormat = RenderTextureFormat.ARGB32; bool forceGrayscaleAfterTexture2D = false; //System.Threading.Thread newThread = new System.Threading.Thread(() => { var loadType = System.IO.Path.GetExtension(path); FREE_IMAGE_LOAD_FLAGS loadFlags = FREE_IMAGE_LOAD_FLAGS.DEFAULT; switch (loadType) { case ".png": loadFlags = FREE_IMAGE_LOAD_FLAGS.PNG_IGNOREGAMMA; break; case ".jpg": case ".jpeg": loadFlags = FREE_IMAGE_LOAD_FLAGS.JPEG_ACCURATE; break; } // Format is stored in 'format' on successfull load. FREE_IMAGE_FORMAT format = FREE_IMAGE_FORMAT.FIF_UNKNOWN; FIBITMAP dib; bool isModifiedEXR = false; char yChar = 'Y'; byte yByte = Convert.ToByte(yChar); char rChar = 'R'; byte rByte = Convert.ToByte(rChar); //byte[] byteArray = File.ReadAllBytes(path); FileStream stream = null; if (Path.GetExtension(path).ToLower() == ".exr") { stream = new FileStream(path, FileMode.Open); stream.Position = 66; isModifiedEXR = (stream.ReadByte() == rByte); if (isModifiedEXR) { Debug.Log("<color=blue>*** This is a modified EXR </color>"); //byteArray[66] = yByte; stream.Position = 66; stream.WriteByte(yByte); stream.Position = 0; } } #if UNITY_STANDALONE_OSX if (stream == null) { stream = new FileStream(path, FileMode.Open); } dib = FreeImage.LoadFromStream(stream, loadFlags, ref format); #else dib = FreeImage.LoadEx(path, loadFlags, ref format); Debug.Log("Used Heap Size After FreeImage.LoadEx: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024); #endif if (stream != null) { stream.Dispose(); GC.Collect(); Debug.Log("Used Heap Size After stream.Dispose: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024); } if (isModifiedEXR) { using (FileStream fs = new FileStream(path, FileMode.Open)) { fs.Position = 66; fs.WriteByte(rByte); fs.Position = 0; } } rtFormat = RenderTextureFormat.ARGB32; try { // Error handling if (dib.IsNull) { return(null); } FREE_IMAGE_TYPE origInputType = FreeImage.GetImageType(dib); //Debug.Log("DIB for :" + path); // read bits per channel of loaded image uint origBPP = FreeImage.GetBPP(dib); var header = FreeImage.GetInfoHeaderEx(dib); //Debug.Log("original BPP:" + origBPP); //Debug.Log("origInputType:" + origInputType); // check here if we need to convert single channel textures to RGB or vice versa based on source input texture type and destination type expected FREE_IMAGE_TYPE destType = FREE_IMAGE_TYPE.FIT_UNKNOWN; switch (origInputType) { case FREE_IMAGE_TYPE.FIT_UINT16: if (!isGrayscale) { destType = FREE_IMAGE_TYPE.FIT_RGBAF; } else { destType = FREE_IMAGE_TYPE.FIT_FLOAT; } break; case FREE_IMAGE_TYPE.FIT_RGBF: case FREE_IMAGE_TYPE.FIT_RGBAF: destType = isGrayscale ? FREE_IMAGE_TYPE.FIT_FLOAT : FREE_IMAGE_TYPE.FIT_RGBAF; break; case FREE_IMAGE_TYPE.FIT_RGB16: case FREE_IMAGE_TYPE.FIT_RGBA16: destType = isGrayscale ? FREE_IMAGE_TYPE.FIT_FLOAT : FREE_IMAGE_TYPE.FIT_RGBAF; break; case FREE_IMAGE_TYPE.FIT_BITMAP: if (isGrayscale) { if (Mathf.IsPowerOfTwo(header.biWidth) && Mathf.IsPowerOfTwo(header.biHeight)) { if (!premultiplyAlpha) { dib = FreeImage.ConvertToGreyscale(dib); } } else { //int w = Mathf.NextPowerOfTwo(header.biWidth); //int h = Mathf.NextPowerOfTwo(header.biHeight); //FIBITMAP bitmap2 = FreeImage.Allocate(w, h, 8); //FreeImage.Paste(bitmap2, dib, 0, 0, 255); //FreeImage.UnloadEx(ref dib); //dib = bitmap2; forceGrayscaleAfterTexture2D = true; dib = FreeImage.ConvertTo32Bits(dib); } } else { dib = FreeImage.ConvertTo32Bits(dib); } destType = FREE_IMAGE_TYPE.FIT_BITMAP; break; } //// premultiply if need be //if (premultiplyAlpha) // FreeImage.PreMultiplyWithAlpha(dib); // convert to destination expected type if (destType != FREE_IMAGE_TYPE.FIT_UNKNOWN && origInputType != destType) { Debug.Log("Trying to convert from:" + origInputType + ", to:" + destType); dib = FreeImage.ConvertToType(dib, destType, false); } //GC.Collect(); Debug.Log("Used Heap Size After FreeImage.ConvertToType: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024); //if (isModifiedEXR && origInputType == FREE_IMAGE_TYPE.FIT_FLOAT) width = (int)FreeImageAPI.FreeImage.GetWidth(dib); height = (int)FreeImageAPI.FreeImage.GetHeight(dib); uint bpp = FreeImage.GetBPP(dib); int pitch = (int)FreeImage.GetPitch(dib); long byteSize = pitch * height; Debug.Log("byteSize: " + byteSize); FREE_IMAGE_TYPE inputType = FreeImage.GetImageType(dib); if (doMipMaps) { byteSize = (long)(byteSize * 1.6666f); } //bytes = new byte[byteSize]; FreeImage.ConvertToRawBits(bytes, dib, pitch, bpp, 0, 0, 0, false); Debug.Log("Used Heap Size After FreeImage.ConvertToRawBits: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024); FreeImage.UnloadEx(ref dib); //GC.Collect(); //Debug.Log("Used Heap Size After FreeImage.UnloadEx: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024); // choose texture format formatToLoad = TextureFormat.ARGB32; Debug.Log("inputType:" + inputType); switch (inputType) { case FREE_IMAGE_TYPE.FIT_FLOAT: formatToLoad = TextureFormat.RFloat; if (origInputType == FREE_IMAGE_TYPE.FIT_UINT16) { rtFormat = RenderTextureFormat.RHalf; } else { rtFormat = RenderTextureFormat.RFloat; } break; case FREE_IMAGE_TYPE.FIT_UINT16: formatToLoad = TextureFormat.RHalf; rtFormat = RenderTextureFormat.RHalf; break; case FREE_IMAGE_TYPE.FIT_RGBA16: formatToLoad = TextureFormat.RGBAHalf; rtFormat = RenderTextureFormat.ARGBHalf; isLinear = true; break; case FREE_IMAGE_TYPE.FIT_RGBAF: formatToLoad = TextureFormat.RGBAFloat; if (origInputType == FREE_IMAGE_TYPE.FIT_RGBA16 || origInputType == FREE_IMAGE_TYPE.FIT_RGB16) { rtFormat = RenderTextureFormat.ARGBHalf; } else { rtFormat = RenderTextureFormat.ARGBFloat; } isLinear = true; break; case FREE_IMAGE_TYPE.FIT_BITMAP: //Iterate over all scanlines switch (bpp) { case 8: { formatToLoad = TextureFormat.Alpha8; rtFormat = RenderTextureFormat.R8; } break; case 16: formatToLoad = TextureFormat.RGBA4444; rtFormat = RenderTextureFormat.ARGB4444; break; case 24: if (FreeImage.IsLittleEndian()) { int length = bytes.Length; // make sure it's a multiple of 3 int factor = length / 3; int adjustedLength = factor * 3; // convert back to RGB for (int i = 0; i < adjustedLength; i += 3) { // convert BGR to RGB var r = bytes[i]; bytes[i] = bytes[i + 2]; bytes[i + 2] = r; } } formatToLoad = TextureFormat.RGB24; rtFormat = RenderTextureFormat.ARGB32; break; case 32: if (forceGrayscaleAfterTexture2D) { formatToLoad = TextureFormat.ARGB32; rtFormat = RenderTextureFormat.R8; } else { if (FreeImage.IsLittleEndian()) { int length = bytes.Length; // make sure it's a multiple of 4 int factor = length / 4; int adjustedLength = factor * 4; for (int j = 0; j < adjustedLength; j += 4) { // convert BGRA to ARGB var a = bytes[j]; var r = bytes[j + 1]; bytes[j] = bytes[j + 3]; bytes[j + 1] = bytes[j + 2]; bytes[j + 2] = r; bytes[j + 3] = a; } } formatToLoad = TextureFormat.ARGB32; rtFormat = RenderTextureFormat.ARGB32; } break; } break; } successfullyLoadedRaw = true; } catch (System.Exception ex) { Debug.LogError("Exception: " + ex.Message); } } //); //newThread.IsBackground = true; //newThread.Start(); //newThread.Join(); //outBPP = origBPP; if (successfullyLoadedRaw) { RenderTexture temp = LoadRawToTexture2D(bytes, width, height, formatToLoad, rtFormat, doMipMaps, isLinear, forceGC, premultiplyAlpha); //GC.Collect(); Debug.Log("Used Heap Size After LoadRawToTexture2D: " + Profiler.GetMonoUsedSizeLong() / 1024 / 1024); return(temp); } return(null); }
private void RenderImage() { Options o = GetOptions(); try { tslInfo.Text = ""; // Validate number of vertices per tile int k = o.VerticesPerTile & (o.VerticesPerTile - 1); if (k != 0) { throw new Exception($"VerticesPerTile value { o.VerticesPerTile} must be a power of 2."); } // Validate number of vertices per tile if (o.VerticesPerTile < 8) { throw new Exception($"VerticesPerTile value { o.VerticesPerTile} must be greater than or equal to 8."); } // load FIBITMAP dib = FreeImage.LoadEx(o.Filename); // calc resolution of tile int tileSizeResolution = o.VerticesPerTile - 1; // show tiles FREE_IMAGE_TYPE it = FreeImage.GetImageType(dib); uint bpp = FreeImage.GetBPP(dib); // Warn if bits-per-pixel is less than 16 if (bpp != 16) { tslInfo.Text = $"Warning! The image provided it's not 16 bits per pixel. 16 bpp grayscale image needed."; } // get height range var range = dib.GetHeightRange(); // load image groupBox1.Text = $"{Path.GetFileName(o.Filename)}, {FreeImage.GetWidth(dib)}x{FreeImage.GetHeight(dib)}, {bpp} bpp, low: {range.X}, high: {range.Y}"; // preview if (!o.SkipPreview) { Image i = Image.FromFile(o.Filename); Bitmap bmp = new Bitmap(i); Graphics g = Graphics.FromImage(bmp); var tiles = MathEx.GetTiles(bmp.Width, bmp.Height, tileSizeResolution); foreach (var item in tiles) { g.DrawRectangle(Pens.LightGreen, item); } // show craters // craterize if (o.Craters > 0) { ce = new CraterEngine() { dib = dib, minRadius = o.CraterMinRadius, maxRadius = o.CraterMaxRadius, numCraters = o.Craters, seed = o.Seed }; ce.BuildCraters(); foreach (var crater in ce.craters) { foreach (var item in crater.craterRidgePoints) { bmp.SetPixel((int)item.X, (int)item.Y, Color.Red); } } } // show image pictureBox1.Image = bmp; } // free FreeImage.Unload(dib); } catch (Exception ex) { tslInfo.Text = ex.Message; } }
public static extern bool FIFSupportsExportType(FREE_IMAGE_FORMAT fif, FREE_IMAGE_TYPE type);
/// <summary> /// Checks whether this plugin can save a bitmap in the desired data type. /// </summary> /// <param name="type">The desired image type.</param> /// <returns>True if this plugin can save bitmaps as the desired type, else false.</returns> public bool SupportsExportType(FREE_IMAGE_TYPE type) { return FreeImage.FIFSupportsExportType(fif, type); }
protected override void ReadHeader(TileLoadInfo info) { int count = 0; List <TilePosition> tilePositions = new List <TilePosition>(); string prefix = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "file format", ""); info.Prefix = prefix; string iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "roi left", "0.0"); double roiLeft = Convert.ToDouble(iniValue, CultureInfo.InvariantCulture); iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "roi top", "0.0"); double roiTop = Convert.ToDouble(iniValue, CultureInfo.InvariantCulture); iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Roi Height", "0.0"); double roiHeight = Convert.ToDouble(iniValue, CultureInfo.InvariantCulture); iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Horizontal Overlap", "0.0"); // This is overlap in % decimal overlapX = Convert.ToDecimal(iniValue); info.OverLapPercentageX = (double)overlapX; iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Vertical Overlap", "0.0"); // This is overlap in % decimal overlapY = Convert.ToDecimal(iniValue); info.OverLapPercentageY = (double)overlapY; iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Horizontal Frames", "0.0"); info.WidthInTiles = Convert.ToInt32(iniValue, CultureInfo.InvariantCulture); iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Vertical Frames", "0.0"); info.HeightInTiles = Convert.ToInt32(iniValue, CultureInfo.InvariantCulture); iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Max Intensity", "0.0"); info.TotalMinIntensity = 0; info.TotalMaxIntensity = Convert.ToDouble(iniValue, CultureInfo.InvariantCulture); info.ScaleMinIntensity = info.TotalMinIntensity; info.ScaleMaxIntensity = info.TotalMaxIntensity; string extension = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Extension", ".ics"); iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Tile Width", "0"); int tileWidth = Convert.ToInt32(iniValue, CultureInfo.InvariantCulture); iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Tile Height", "0"); int tileHeight = Convert.ToInt32(iniValue, CultureInfo.InvariantCulture); iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Tile Bits Per Pixel", "0"); info.ColorDepth = Convert.ToInt32(iniValue, CultureInfo.InvariantCulture); iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Tile Image Type", "0"); int tileImageType = Convert.ToInt32(iniValue, CultureInfo.InvariantCulture); iniValue = IniParser.IniFile.GetIniFileString(this.FilePath, info_ini_name, "Pixels Per Micron", "1.0"); info.OriginalPixelsPerMicron = Convert.ToDouble(iniValue, CultureInfo.InvariantCulture); // This file format provides a list of tiles and their position relative // to the left, top of the first region of interest. DirectoryInfo dir = new DirectoryInfo(this.DirectoryPath); FileInfo[] filesInDir = dir.GetFiles(prefix + "*" + extension); count = info.WidthInTiles * info.HeightInTiles; Tile[] validTiles = new Tile[count]; Tile.IsCompositeRGB = false; // Check whether all the filenames will have are valid for (int i = 1; i <= count; i++) { string filename = BuildExpectedFilename(prefix, i, extension); string fullpath = this.DirectoryPath + Path.DirectorySeparatorChar + filename; validTiles[i - 1] = new Tile(fullpath, i, tileWidth, tileHeight); } int width = 0; int height = 0; int bpp = 8; FREE_IMAGE_TYPE type = FREE_IMAGE_TYPE.FIT_BITMAP; // Find the first tile that exists to get the sizes and color depth etc // but check all bool oneNotFound = false, atLeastOneFound = false; foreach (Tile tile in validTiles) { if (System.IO.File.Exists(tile.FilePath)) { if (!atLeastOneFound) { FreeImageAlgorithmsBitmap fib = tile.LoadFreeImageBitmap(); width = fib.Width; height = fib.Height; bpp = fib.ColorDepth; type = fib.ImageType; fib.Dispose(); atLeastOneFound = true; } } else { oneNotFound = true; } } if (!atLeastOneFound) // No images at all! { throw (new MosaicReaderException("No images found. Expecting prefix " + prefix + " as in seq file.")); } if (oneNotFound) { MessageBox.Show("At least 1 image is missing from the mosaic.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning); } foreach (Tile tile in validTiles) { if (this.ThreadController.ThreadAborted) { return; } Point position = new Point(); int row, col; // fileWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(filepath); // Ignore files in the directory that have shorter names than we expect. // if (fileWithoutExtension.Length < mosaicInfo.Fileinfo.Prefix.Length) // continue; // fileWithoutPrefix = fileWithoutExtension.Substring(prefix.Length); // fileNumber = Version2SequenceFileReader.ParseIntStringWithZeros(fileWithoutPrefix); row = ((tile.TileNumber - 1) / info.WidthInTiles) + 1; if ((row % 2) > 0) { // Odd row reversed order col = ((tile.TileNumber - 1) % info.WidthInTiles) + 1; } else { // Even row nornal order col = info.WidthInTiles - ((tile.TileNumber - 1) % info.WidthInTiles); } decimal overlapXInpixels = (overlapX / 100.0M) * (decimal)tileWidth; decimal overlapYInpixels = (overlapY / 100.0M) * (decimal)tileHeight; position.X = (int)Math.Round(((decimal)width - overlapXInpixels) * ((decimal)col - 1.0M)); position.Y = (int)Math.Round(((decimal)height - overlapYInpixels) * ((decimal)row - 1.0M)); tile.OriginalPosition = position; tile.Width = width; tile.Height = height; tile.ColorDepth = bpp; tile.FreeImageType = type; info.Items.Add(tile); } }
public static extern FIBITMAP AllocateT(FREE_IMAGE_TYPE ftype, int width, int height, int bpp, uint red_mask, uint green_mask, uint blue_mask);
public FreeImageAlgorithmsBitmap(int width, int height, FREE_IMAGE_TYPE type, int colorDepth) { FIBITMAP dib = FreeImage.AllocateT(type, width, height, colorDepth, FreeImage.FI_RGBA_RED_MASK, FreeImage.FI_RGBA_GREEN_MASK, FreeImage.FI_RGBA_BLUE_MASK); if (dib.IsNull) { throw new Exception("Unable to create bitmap."); } this.ReplaceDib(dib); }
public static extern bool FIFSupportsICCProfiles(FREE_IMAGE_FORMAT format, FREE_IMAGE_TYPE ftype);
public void StretchImageToType(FREE_IMAGE_TYPE type, double max) { FIBITMAP tmp_dib = FreeImage.StretchImageToType(this.Dib, type, max); this.ReplaceDib(tmp_dib); }
static void Main(string[] args) { if (args.Length < 2) { PrintHelp(); return; } try { string inputFile = args[0]; string outputFile = args[1]; Console.WriteLine(String.Format("Loading file: {0}", inputFile)); FIBITMAP image = FreeImage.LoadEx(inputFile); // Make sure the image is one of the supported types FREE_IMAGE_TYPE imgType = FreeImage.GetImageType(image); switch (imgType) { case FREE_IMAGE_TYPE.FIT_INT16: Console.WriteLine("Detected 16-bit short"); break; case FREE_IMAGE_TYPE.FIT_INT32: Console.WriteLine("Detected 32-bit int"); break; case FREE_IMAGE_TYPE.FIT_UINT16: Console.WriteLine("Detected 16-bit ushort"); break; case FREE_IMAGE_TYPE.FIT_UINT32: Console.WriteLine("Detected 32-bit uint"); break; default: Console.WriteLine(String.Format("Unsupported file type: {0}", imgType.ToString())); return; } uint width = FreeImage.GetWidth(image); uint height = FreeImage.GetHeight(image); uint fileBPP = FreeImage.GetBPP(image); // Allocate new RGB Image FIBITMAP newMap = FreeImage.Allocate((int)width, (int)height, 8 /*BitsPerPixel*/ * 3); RGBQUAD outQuad = new RGBQUAD(); // Multiplier for the byte offset into the scaline int iterations = 0; int lateralMultipler = fileBPP == 16 ? 2 : 4; for (uint x = 0; x < width; ++x, ++iterations) { float progress = ((float)(iterations)) / ((float)(width * height)); Console.Write(String.Format("\rProgress {0:000.0}% ", progress * 100.0f)); for (uint y = 0; y < height; ++y, ++iterations) { IntPtr line = FreeImage.GetScanLine(image, (int)y); if (fileBPP >= 16) { line = new IntPtr(line.ToInt64() + lateralMultipler * x); if (imgType == FREE_IMAGE_TYPE.FIT_UINT16) { ushort value = (ushort)System.Runtime.InteropServices.Marshal.ReadInt16(line); outQuad.rgbRed = (byte)(value / 256); outQuad.rgbGreen = (byte)(value % 256); } else if (imgType == FREE_IMAGE_TYPE.FIT_UINT32) { uint value = (uint)System.Runtime.InteropServices.Marshal.ReadInt32(line); outQuad.rgbRed = (byte)(value / 256); outQuad.rgbGreen = (byte)(value % 256); } else if (imgType == FREE_IMAGE_TYPE.FIT_INT16) { short value = (short)System.Runtime.InteropServices.Marshal.ReadInt16(line); outQuad.rgbRed = (byte)(value / 256); outQuad.rgbGreen = (byte)(value % 256); } else if (imgType == FREE_IMAGE_TYPE.FIT_INT32) { int value = (int)System.Runtime.InteropServices.Marshal.ReadInt32(line); outQuad.rgbRed = (byte)(value / 256); outQuad.rgbGreen = (byte)(value % 256); } FreeImage.SetPixelColor(newMap, x, y, ref outQuad); } else { } } } Console.WriteLine(" "); //empty space Console.WriteLine(String.Format("Writing file: {0}", outputFile)); if (FreeImage.SaveEx(newMap, outputFile)) { Console.WriteLine("Finished"); } else { Console.WriteLine("ERROR: Failed to write file"); } } catch (Exception ex) { Console.WriteLine("ERROR: "); Console.Write(ex.Message); } }