public bool LoadTextures(FileInfo[] textureFiles) { bool success = false; textures.Clear(); foreach (FileInfo texFile in textureFiles) { if (texFile.Exists && !textures.ContainsKey(texFile.Name)) { Bitmap tga = new TargaImage(texFile.FullName).Image; int id = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, id); BitmapData data = tga.LockBits(new Rectangle(0, 0, tga.Width, tga.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0, OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0); tga.UnlockBits(data); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear); textures.Add(texFile.Name, id); } } return(success); }
// Reads textures from jpg, png, and tga files public static Texture2D LoadTexture(BasicEffect effect, string texturePath) { Texture2D texture; if (texturePath.ToLower().EndsWith(".tga")) { TargaImage image = new TargaImage(texturePath); texture = new Texture2D(effect.GraphicsDevice, image.Header.Width, image.Header.Height); Color[] data = new Color[image.Header.Height * image.Header.Width]; for (int y = 0; y < image.Header.Height; y++) { for (int x = 0; x < image.Header.Width; x++) { System.Drawing.Color color = image.Image.GetPixel(x, y); data[y * image.Header.Width + x] = new Color(color.R, color.G, color.B, color.A); } } image.Dispose(); texture.SetData(data); } else { FileStream stream = new FileStream(texturePath, FileMode.Open); texture = Texture2D.FromStream(effect.GraphicsDevice, stream); stream.Close(); } return(texture); }
private void panelGrid_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(typeof(ToolBoxItem))) { this.DropToolBoxItem(e.Data.GetData(typeof(ToolBoxItem)) as ToolBoxItem, new Point(e.X, e.Y)); } else if (e.Data.GetDataPresent("FileNameW")) { string[] paths = (string[])e.Data.GetData("FileNameW"); foreach (string path in paths) { Bitmap img = null; if (path.ToLower().EndsWith("tga")) { img = TargaImage.LoadTargaImage(path); } else { img = new Bitmap(path); } img.ReplaceColor(Editor.TransparentColor, Color.Transparent); Sprite sprite = new Sprite { Img = img, Path = null }; this.AddTile(sprite, this.PointToClient(new Point(e.X, e.Y))); } } }
private void PopulateFolder(string dir, IEnumerable <string> images) { int idx = this.toolBox1.AddTab(new DirectoryInfo(dir).Name); this.toolBox1[idx].View = ViewMode.LargeIcons; this.toolBox1[idx].ToolTip = dir; foreach (string path in images) { Bitmap img = null; if (path.ToLower().EndsWith("tga")) { img = TargaImage.LoadTargaImage(path); } else { img = new Bitmap(path); } img.ReplaceColor(Editor.TransparentColor, Color.Transparent); Sprite.Filename2path[Path.GetFileName(path)] = path; this.toolBox1.LargeImageList.Images.Add(img); this.toolBox1[idx].SelectedItemIndex = 0; int item = this.toolBox1[idx].AddItem(Path.GetFileNameWithoutExtension(path), 0, this.toolBox1.LargeImageList.Images.Count - 1); this.toolBox1[idx][item].ToolTip = String.Format("{2} {0} x {1}", img.Width, img.Height, Path.GetFileName(path)); this.toolBox1[idx][item].Object = new Sprite { Path = path, Img = img }; } }
private BitmapSource LoadTGA(byte[] bytes) { System.Drawing.Bitmap bmp = TargaImage.LoadTargaImage(bytes); BitmapSource bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bmp.GetHbitmap(), IntPtr.Zero, System.Windows.Int32Rect.Empty, BitmapSizeOptions.FromWidthAndHeight(bmp.Width, bmp.Height)); bs.Freeze(); return(bs); }
private Bitmap LoadImage(string filename) { switch (Path.GetExtension(filename)) { case ".tga": return(TargaImage.LoadTargaImage(filename)); default: return(new Bitmap(filename)); } }
private void previewToolStripMenuItem_Click(object sender, EventArgs e) { ImageSize imgSize; //string imgName = (tex2D.getFileFormat() == ".tga") ? "exec\\" + "preview00" : "exec\\" + "preview"; string imgName = "exec\\preview" + tex2D.getFileFormat(); if (File.Exists("exec\\preview.tga")) { File.Delete("exec\\preview.tga"); } if (File.Exists("exec\\preview.dds")) { File.Delete("exec\\preview.dds"); } if (tex2D.imgList.Count != 1) { imgSize = tex2D.imgList.Where(img => (img.imgSize.width <= 512 || img.imgSize.height <= 512) && img.offset != -1).Max(image => image.imgSize); } else { imgSize = tex2D.imgList.First().imgSize; } tex2D.extractImage(imgSize.ToString(), ME3Directory.cookedPath, imgName); if (File.Exists(Path.GetFullPath(imgName))) { if (pictureBox.Image != null) { pictureBox.Image.Dispose(); } pictureBox.SizeMode = PictureBoxSizeMode.AutoSize; if (tex2D.getFileFormat() == ".dds") { DDSImage ddsImage = new DDSImage(imgName); pictureBox.Image = ddsImage.ToPictureBox(pictureBox.Width, pictureBox.Height); } else // .tga { TargaImage ti = new TargaImage(imgName); pictureBox.Image = ti.Image; } pictureBox.Refresh(); listView1.Visible = false; panelImage.Visible = true; if (File.Exists(imgName)) { File.Delete(imgName); } } }
/// <summary> /// Reads the header of a TGA image. /// </summary> /// <param name="stream">Fully formatted TGA image.</param> /// <returns>Length of header.</returns> protected override long Load(Stream stream) { base.Load(stream); // Class already written. Complex and I don't want to rewrite it. using (BinaryReader br = new BinaryReader(stream, Encoding.Default, true)) TargaImage.LoadTGAHeaderInfo(br, header); Width = header.Width; Height = header.Height; return(stream.Position); }
private void BGW_DoWork(object sender, DoWorkEventArgs e) { bool ReplaceFlag = false, NameDiffFlag = false; int FileCount = PendingFile.Items.Count, Counter = 0; if (!Directory.Exists(SPath.Text)) { Directory.CreateDirectory(SPath.Text); } foreach (object item in PendingFile.Items) { if (BGW.CancellationPending) { BGW.ReportProgress(0, "Abort"); break; } string FCompletePath = item.ToString(); string FDirectory = Path.GetDirectoryName(Path.GetDirectoryName(Path.GetDirectoryName(FCompletePath))).Split(new char[] { '\\', '/' }).Last(); string FName = Path.GetFileNameWithoutExtension(FCompletePath); string SCompletePath = SPath.Text + "/" + FDirectory + " - " + FName + ".png"; if (!NameDiffFlag && !ReplaceFlag && File.Exists(SCompletePath)) { DialogResult Res = MessageBox.Show("File name conflicted. Settings you choose later will apply on all files.\nClick \"Retry\" to Name as different.\nClick \"Ignore\" to replace.\nClick \"Abort\" to cancel whole work.", "File Confliction", MessageBoxButtons.AbortRetryIgnore); switch (Res) { case DialogResult.Abort: BGW.CancelAsync(); continue; case DialogResult.Ignore: ReplaceFlag = true; break; case DialogResult.Retry: NameDiffFlag = true; break; } } if (NameDiffFlag) { SCompletePath = SPath.Text + "/" + FDirectory + " - " + FName + Guid.NewGuid().ToString().Substring(0, 4) + ".png"; } TargaImage TGA = new TargaImage(FCompletePath); TGA.Image.Save(SCompletePath, ImageFormat.Png); Counter++; BGW.ReportProgress(Counter / FileCount * 100, Counter + "/" + FileCount); } }
public TgaSequenceConverter() { _tgaLoader = new TargaImageLoader(); _tga = new TargaImage(); _bmp = new BitmapImage(); _converter = new TgaToBmpConverter(); _frameRate = 30; _frameBlendingIndex = 0; _frameProcessIndex = 0; _deleteOnClose = false; _compressor = null; }
private void LoadImage(byte[] data) { try { TargaImage image = new TargaImage(data); imagePreview.Source = Imaging.CreateBitmapSourceFromHBitmap(image.Image.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); txtHeight.Text = image.Image.Height.ToString(); txtWidth.Text = image.Image.Width.ToString(); } catch { } }
public void LoadSave() { //using (OpenFileDialog d = new OpenFileDialog()) //{ //if (d.ShowDialog() == DialogResult.OK) //{ TargaImage image = new TargaImage(@"F:\3DContents\Modelos\Lightning\c001_01.tga"); MemoryStream ms = new MemoryStream(image.Image.Width * image.Image.Height * 32); var decoders = ImageCodecInfo.GetImageDecoders(); image.Image.Save(ms, ImageFormat.Bmp); File.WriteAllBytes("temp.bmp", ms.ToArray()); var bmpData = image.Image.LockBits(new System.Drawing.Rectangle(0, 0, image.Image.Width, image.Image.Height), ImageLockMode.ReadWrite, image.Image.PixelFormat); // Get the address of the first line. IntPtr ptr = bmpData.Scan0; // Declare an array to hold the bytes of the bitmap. int bytes = Math.Abs(bmpData.Stride) * image.Image.Height; byte[] rgbValues = new byte[bytes]; //Copy the RGB values into the array. //System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes); // Set every third value to 255. A 24bpp bitmap will look red. //32bpp - BGRA for (int counter = 0; counter < rgbValues.Length; counter += 3) { rgbValues[counter] = 255; } // Copy the RGB values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes); // Unlock the bits. image.Image.UnlockBits(bmpData); image.Image.Save("temp1.bmp", ImageFormat.Bmp); Process.Start("temp1.bmp"); //var g = ((TestApplication)(TestApplication.CurrentApplication)).Form.CreateGraphics(); //g.DrawImage(image.Image, 0, 0); //} //} }
public DoDLevel(string name, string habRelativePath, string levelBaseFullPath, string levelFullPath) { this.name = name; this.habRelativePath = habRelativePath; string briefingImageFullPath = Path.Combine(levelFullPath, "briefing.tga"); if (File.Exists(briefingImageFullPath)) { brefingImage = TargaImage.LoadTargaImage(Path.Combine(levelFullPath, "briefing.tga")); } else { brefingImage = TargaImage.LoadTargaImage(Path.Combine(levelBaseFullPath, "default_briefing.tga")); } }
public bool Export(string root, string package, string assetName, ExportType exportType, string destination, bool forceTgaToPng = false) { var tmpDir = GetTMPDir(); if (Directory.Exists(tmpDir)) { Directory.Delete(tmpDir, true); } Directory.CreateDirectory(tmpDir); // .\umodel.exe -game=ue3 -path="C:\Program Files (x86)\Steam\steamapps\common\HatinTime\HatinTimeGame\EditorCookedPC" -export HatinTime_Music_Metro4 Act_4_Pink_Paw_Station -sounds -out=".\test" var res = Run($"-game=ue3 -path=\"{root}\" -3rdparty -export {package} {assetName}{(exportType == ExportType.SoundNodeWave ? " -sounds" : " " + exportType.ToString())} -out=\"{tmpDir}\""); if (!res) { return(false); } var extension = GetExtensionForType(exportType); var path = Path.Combine(tmpDir, package, exportType.ToString(), assetName + extension); Debug.WriteLine("ExceptedPath: " + path); if (File.Exists(path)) { if (File.Exists(destination)) { File.Delete(destination); } if (forceTgaToPng && exportType == ExportType.Texture2D) { using (var b = new TargaImage(path)) { b.Image.Save(destination, ImageFormat.Png); } } else { File.Move(path, destination); } return(true); } return(false); }
private void PreviewTex(ZipReader.ZipEntryFull ent, bool dds) { try { Bitmap img; if (dds) { byte[] data = ent.Extract(true); if (data == null) { throw new NullReferenceException("Data returned was null"); } DDSPreview ddsimg = new DDSPreview(data); //img = DDSImage.ToBitmap(ddsimg.GetMipData(), ddsimg.Format, (int)ddsimg.Width, (int)ddsimg.Height); img = ddsimg.ToBitmap(); } else { ent.Extract(false, "preview.tga"); img = new TargaImage("preview.tga").Image; File.Delete("preview.tga"); } if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); } if (_resize) { pictureBox1.Image = resizeImage(img, new System.Drawing.Size(512, 512)); } else { pictureBox1.Image = img; } pictureBox1.Visible = true; pictureBox1.Refresh(); } catch (Exception exc) { MessageBox.Show("An error occurred: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void btnNeutralityFlag_Click(object sender, EventArgs e) { OpenFileDialog fd = new OpenFileDialog(); fd.Filter = "Targa File (*.tga)|*.tga"; fd.ShowDialog(this); if (fd.FileName == "") { btnNeutralityFlag.BackColor = Color.LightPink; NewCountryFlagPicture.Image = null; } else { Bitmap newFlag = TargaImage.LoadTargaImage(fd.FileName); NewCountryFlagPicture.Image = newFlag; btnNeutralityFlag.BackColor = Color.LightGreen; } CreateNewCountryButton.Enabled = NewCountryFieldsCheck(); }
public void SetData(byte[] data, string filename) { mName = filename; try { using (MemoryStream ms = new MemoryStream(data)) { if (mIsTga) { using (TargaImage tga = new TargaImage(ms)) { ImagePreview = tga.Image.Clone() as Image; } } else { ImagePreview = Image.FromStream(ms); } } } catch { ImagePreview = GrfEditor.Library.Properties.Resources.image_error; } }
/// <summary> /// Tries to detect the image format of the given data by /// inspecting the header only. /// </summary> /// <param name="data"></param> /// <returns></returns> public static ImageFileInfo DetectImageFormat(ReadOnlySpan <byte> data) { ImageFileInfo info; if (StbNative.GetPngInfo(data, out info.width, out info.height, out info.hasAlpha)) { info.format = ImageFileFormat.PNG; return(info); } if (StbNative.GetBitmapInfo(data, out info.width, out info.height, out info.hasAlpha)) { info.format = ImageFileFormat.BMP; return(info); } using var jpegDecompressor = new JpegDecompressor(); if (jpegDecompressor.ReadHeader(data, out info.width, out info.height)) { info.hasAlpha = false; info.format = ImageFileFormat.JPEG; return(info); } if (TargaImage.DetectTga(data, out info)) { return(info); } // Not a very good heuristic if (data.Length == 256 * 256) { info.width = 256; info.height = 256; info.hasAlpha = true; info.format = ImageFileFormat.FNTART; return(info); } return(info); }
/// <summary> /// Loads a Bitmap from a file. /// </summary> /// <param name="FileName"></param> public void LoadFromFile(string FileName) { try { { if ((System.IO.Path.GetExtension(FileName)).ToUpper() == ".TGA") { TargaImage TI = new TargaImage(FileName); Bitmap = TI.Image; Bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX); Bitmap.RotateFlip(RotateFlipType.RotateNoneFlipX); } else { Bitmap = (Bitmap)System.Drawing.Bitmap.FromFile(FileName); } } } catch (Exception E) { System.Windows.Forms.MessageBox.Show(E.Message); } }
public bool Identify(System.IO.Stream stream) { using (var reader = new Toolbox.Library.IO.FileReader(stream, true)) { if (reader.BaseStream.Length < 30) { return(false); } reader.Position = reader.BaseStream.Length - 18; bool IsValidMagic = reader.ReadString(10) == MagicFileConstant; bool IsTga = IsValidMagic || Utils.GetExtension(FileName) == ".tga"; if (IsTga) { TargaImage tga = new TargaImage(); IsTga = tga.IsSupportedTGA(stream); stream.Position = 0; } return(IsTga); } }
public static Bitmap LoadBitmapFromFile(string path, SegaSaturnColor transparentColor = null) { if (Path.GetExtension(path).ToLowerInvariant() == ".bin") { using (Stream stream = File.Open(path, FileMode.Open)) { using (BinaryReader streamReader = new BinaryReader(stream)) { Bitmap bin = new Bitmap(streamReader.ReadUInt16(), streamReader.ReadUInt16(), PixelFormat.Format32bppArgb); using (BmpPixelSnoop tmp = new BmpPixelSnoop(bin)) { for (int y = 0; y < tmp.Height; ++y) { for (int x = 0; x < tmp.Width; ++x) { tmp.SetPixel(x, y, new SegaSaturnColor(streamReader.ReadUInt16())); } } } return(bin); } } } if (Path.GetExtension(path).ToLowerInvariant() == ".tga") { Bitmap tga = TargaImage.LoadTargaImage(path); if (transparentColor != null) { tga.ReplaceColor(transparentColor, Color.Transparent); } return(tga); } Bitmap bitmap = (Bitmap)Bitmap.FromFile(path); if (transparentColor != null) { bitmap.ReplaceColor(transparentColor, Color.Transparent); } return(bitmap); }
public static Bitmap GetBitmap(string path) { try { Bitmap img = null; if (path.ToLower().EndsWith("tga")) { img = TargaImage.LoadTargaImage(path); } else { img = new Bitmap(path); } img.ReplaceColor(Editor.TransparentColor, Color.Transparent); return(img); } catch (Exception ex) { Program.Logger.Error(String.Format("Fail to load texture : {0}", path), ex); throw new InvalidOperationException(String.Format("Fail to load texture : {0}", path), ex); } }
private async Task ExtractAll() { await Task.Run(delegate { foreach (var chunk in Parser.Chunks) { string path = System.IO.Path.Combine(Destination, chunk.Name); if (File.Exists(path)) { continue; } Dispatcher.Invoke(delegate { LoadingBody.Text = path; LoadingProgress.Maximum = Parser.Chunks.Count; LoadingProgress.Value++; }); Parser.ExtractFile(Destination, chunk); if (tgaConvert == true) { if (System.IO.Path.GetExtension(chunk.Name) == ".tga") { using (var targa = TargaImage.LoadTargaImage(path)) { using (var fileStream = File.OpenWrite( System.IO.Path.Combine(Destination, chunk.Name.Remove(chunk.Name.Length - 4, 4) + ".png"))) { targa.Save(fileStream, ImageFormat.Png); } } File.Delete(path); } } } }); }
private void SaveImage(Texture2D tex, string dir) { Bitmap original = null; if (tex.IsDDS) { original = DDS.LoadImage(tex.Image, _alpha); if (_flip) { original.RotateFlip(RotateFlipType.RotateNoneFlipY); } } else { // Assumimg it is TGA, alpha?? var tga = new TargaImage(new MemoryStream(tex.Image)); original = tga.Image; if (!_flip) // tga already flipped { original.RotateFlip(RotateFlipType.RotateNoneFlipY); } } original.Save(Path.Combine(dir, tex.Name + ".png")); }
void ExtractTarGA(string path, StinkyFile.ManifestChunk chunk, StinkyFile.Primitive.RefPrim <bool> success) { try { using (var targa = TargaImage.LoadTargaImage(path)) { using (var fileStream = File.OpenWrite( System.IO.Path.Combine(Installation.DestinationDirectory, chunk.Name.Remove(chunk.Name.Length - 4, 4) + ".png"))) { targa.Save(fileStream, ImageFormat.Png); } } var destpath = Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + ".png"); Installation.FileChanged(destpath, FileChange.ADD); File.Delete(path); } catch (Exception e) { success.Value = false; return; } success.Value = true; }
/// <summary> /// マテリアルをUnity用に変換する /// </summary> /// <returns>Unity用マテリアル</returns> /// <param name='material_index'>PMX用マテリアルインデックス</param> /// <param name='is_transparent'>透過か</param> private Material ConvertMaterial(uint material_index, bool is_transparent) { var material = format_.material_list.material[material_index]; //先にテクスチャ情報を検索 Texture2D main_texture = null; if (material.usually_texture_index == uint.MaxValue) { main_texture = Texture2D.whiteTexture; } else { var texture_file_name = format_.texture_list.texture_file[material.usually_texture_index]; var path = format_.meta_header.folder + "/" + texture_file_name; if (File.Exists(path)) { if (material.usually_texture_index < format_.texture_list.texture_file.Length) { if (Path.GetExtension(texture_file_name).ToUpper() == ".DDS") { main_texture = Texture2D.whiteTexture; main_texture = DDSImage.LoadDDS(path); main_texture.wrapModeV = TextureWrapMode.MirrorOnce; } else if (Path.GetExtension(texture_file_name).ToUpper() == ".BMP") { main_texture = BMPLoader.LoadBMP(path).ToTexture2D(); } else if (Path.GetExtension(texture_file_name).ToUpper() == ".TGA") { try { var bitmap = TargaImage.LoadTargaImage(path); main_texture = new Texture2D(bitmap.Width, bitmap.Height); var stream = new MemoryStream(); bitmap.Save(stream, ImageFormat.Png); main_texture.LoadImage(stream.ToArray()); stream.Close(); main_texture.Apply(); } catch (Exception e) { Debug.Log("TGA Exception"); Debug.Log(texture_file_name); Debug.LogError(e.Message); main_texture = Texture2D.whiteTexture; } //main_texture = CreateTexture(path); } else { main_texture = new Texture2D(1, 1, TextureFormat.RGBA32, false); main_texture.LoadImage(File.ReadAllBytes(path)); // Fill the texture field } //main_texture.alphaIsTransparency = true; } } else { main_texture = Texture2D.whiteTexture; } } var result = new Material(Resources.Load <Material>("Transparent")) { renderQueue = (int)(3000 + material_index) }; result.SetTexture("_BaseColorMap", main_texture); result.SetVector("_BaseColor", material.diffuse_color); result.SetFloat("_TransparentSortPriority", material_index); result.name = format_.material_list.material[material_index].name; try { foreach (var m in GameObject.Find("Preview Builder Main").GetComponent <PreviewBuilder.PreviewBuilder>() .MaterialExtraConfigurationList.Materials) { foreach (var item in m.MaterialName) { if (result.name.ToUpper().Contains(item.ToUpper())) { result.SetFloat("_AlphaCutoffPrepass", float.Parse(m.Throttle)); Debug.Log($"{result.name} {m.Throttle}"); goto Found; } else { var defaultValue = (from t in GameObject.Find("Preview Builder Main") .GetComponent <PreviewBuilder.PreviewBuilder>().MaterialExtraConfigurationList.Materials where t.Name == "Default" select t).FirstOrDefault(); result.SetFloat("_AlphaCutoffPrepass", float.Parse(defaultValue.Throttle)); } } } } catch (Exception e) { Debug.LogError(e.Message); } Found: return(result); }
private static Texture LoadTga(string path) { return(TargaImage.LoadTargaImage(path)); }
/// <summary> /// Loads image from stream. /// </summary> /// <param name="stream">Full image stream.</param> /// <param name="Format">Detected Format.</param> /// <param name="extension">File Extension. Used to determine format more easily.</param> /// <param name="maxWidth">Maximum width to allow when loading. Resized if enforceResize = true.</param> /// <param name="maxHeight">Maximum height to allow when loading. Resized if enforceResize = true.</param> /// <param name="enforceResize">True = Resizes image to match either maxWidth or maxHeight.</param> /// <param name="header">DDS header of image.</param> /// <param name="mergeAlpha">ONLY valid when enforceResize is true. True = Flattens alpha down, directly affecting RGB.</param> /// <returns>List of Mipmaps.</returns> internal static List <MipMap> LoadImage(Stream stream, out Format Format, string extension, int maxWidth, int maxHeight, bool enforceResize, out DDSGeneral.DDS_HEADER header, bool mergeAlpha) { // KFreon: See if image is built-in codec agnostic. header = null; Format = ImageFormats.ParseFormat(stream, extension, ref header); List <MipMap> MipMaps = null; switch (Format.SurfaceFormat) { case ImageEngineFormat.BMP: case ImageEngineFormat.JPG: case ImageEngineFormat.PNG: MipMaps = WIC_Codecs.LoadWithCodecs(stream, maxWidth, maxHeight, false); break; case ImageEngineFormat.DDS_DXT1: case ImageEngineFormat.DDS_DXT2: case ImageEngineFormat.DDS_DXT3: case ImageEngineFormat.DDS_DXT4: case ImageEngineFormat.DDS_DXT5: if (WindowsWICCodecsAvailable) { MipMaps = WIC_Codecs.LoadWithCodecs(stream, maxWidth, maxHeight, true); } else { MipMaps = DDSGeneral.LoadDDS(stream, header, Format, maxHeight > maxWidth ? maxHeight : maxWidth); } break; case ImageEngineFormat.DDS_ARGB: case ImageEngineFormat.DDS_A8L8: case ImageEngineFormat.DDS_RGB: case ImageEngineFormat.DDS_ATI1: case ImageEngineFormat.DDS_ATI2_3Dc: case ImageEngineFormat.DDS_G8_L8: case ImageEngineFormat.DDS_V8U8: MipMaps = DDSGeneral.LoadDDS(stream, header, Format, maxHeight > maxWidth ? maxHeight : maxWidth); break; case ImageEngineFormat.TGA: var img = new TargaImage(stream); byte[] pixels = UsefulThings.WinForms.Imaging.GetPixelDataFromBitmap(img.Image); WriteableBitmap wbmp = UsefulThings.WPF.Images.CreateWriteableBitmap(pixels, img.Image.Width, img.Image.Height); var mip1 = new MipMap(wbmp); MipMaps = new List <MipMap>() { mip1 }; img.Dispose(); break; default: throw new InvalidDataException("Image format is unknown."); } if (MipMaps == null || MipMaps.Count == 0) { throw new InvalidDataException("No mipmaps loaded."); } // KFreon: No resizing requested if (maxHeight == 0 && maxWidth == 0) { return(MipMaps); } // KFreon: Test if we need to resize var top = MipMaps.First(); if (top.Width == maxWidth || top.Height == maxHeight) { return(MipMaps); } int max = maxWidth > maxHeight ? maxWidth : maxHeight; // KFreon: Attempt to resize var sizedMips = MipMaps.Where(m => m.Width > m.Height ? m.Width <= max : m.Height <= max); if (sizedMips != null && sizedMips.Any()) // KFreon: If there's already a mip, return that. { MipMaps = sizedMips.ToList(); } else if (enforceResize) { // Get top mip and clear others. var mip = MipMaps[0]; MipMaps.Clear(); MipMap output = null; int divisor = mip.Width > mip.Height ? mip.Width / max : mip.Height / max; output = Resize(mip, 1f / divisor, mergeAlpha); MipMaps.Add(output); } return(MipMaps); }
public TexTrend(byte[] textureData, string textureFilePath) { //A QUICK NOTE: //textureFilePath doesn't have to be a valid path in this routine; it's kept for record only. //This is useful if you need to store the file's name (e.g. for labeled viewing later on) try { //validations; this guys have to be valid for this to work if (textureData == null || string.IsNullOrEmpty(textureFilePath)) return; //final global image array var imageArray = new List<Image>(); //make sure there's data to work on! if (textureData.Length > 0) { //extension is used to check the format of the image var ext = Path.GetExtension(textureFilePath).ToLower(); //try signature verification first; foolproof checks const uint dds = 1145328416; const uint png = 2303741511; //read signature of the bytes var readCc = Methods.ReadFourCc(textureData); //verify switch (readCc) { //change extension variable to .dds to trip the checks below case dds: ext = @".dds"; break; //change extension variable to .png to trip the checks below case png: ext = @".png"; break; } //validate the extension so we know how to use the data switch (ext) { //DirectDraw textures are handled via managed DirectX 9 //NOTE: TT Games just renames *.dds files to *.tex case @".tex": case @".dds": //load the raw bytes directly into the DDS handler var newImages = new DDS_IMAGE(textureData); //append the new images to the image collection (if valid) if (newImages.images.Length > 0) imageArray.AddRange(newImages.images); break; //'Normal' images are handled natively by .NET case @".jpeg": case @".jpg": case @".raw": case @".bmp": case @".png": case @".gif": case @".giff": case @".tif": case @".tiff": //load image directly from a memory stream (don't load the bytes from the file again!) var newImage = Image.FromStream(new MemoryStream(textureData)); //append the new image to the image collection (if valid) if (newImage.Height > 0 && newImage.Width > 0) imageArray.Add(newImage); break; //Targa (TruVision) images get handled by a library case @".tga": //load image directly from a memory stream (don't load the bytes from the file again!) var tga = new TargaImage(new MemoryStream(textureData)); var tgaImage = tga.Image; //append the new image to the image collection (if valid) if (tgaImage != null) if (tgaImage.Height > 0 && tgaImage.Width > 0) imageArray.Add(tgaImage); break; //Anything else isn't supported and can't be processed default: MessageBox.Show(@"Texture format was invalid; unrecognised file extension. Please consult the supported file-types list."); return; } } //if any images ended up getting processed, apply all of them to the global array if (imageArray.Count > 0) Images = imageArray.ToArray(); //apply the other globals needed FilePath = textureFilePath; } catch (Exception ex) { MessageBox.Show($"Texture byte parse error:\n\n{ex}"); //ignore all errors } }
internal static List <MipMap> LoadImage(Stream imageStream, AbstractHeader header, int maxDimension, double scale, ImageFormats.ImageEngineFormatDetails formatDetails) { imageStream.Seek(0, SeekOrigin.Begin); List <MipMap> MipMaps = null; int decodeWidth = header.Width > header.Height ? maxDimension : 0; int decodeHeight = header.Width < header.Height ? maxDimension : 0; switch (header.Format) { case ImageEngineFormat.DDS_DXT1: case ImageEngineFormat.DDS_DXT2: case ImageEngineFormat.DDS_DXT3: case ImageEngineFormat.DDS_DXT4: case ImageEngineFormat.DDS_DXT5: MipMaps = WIC_Codecs.LoadWithCodecs(imageStream, decodeWidth, decodeHeight, scale, true, formatDetails); if (MipMaps == null) { // Windows codecs unavailable/failed. Load with mine. MipMaps = DDSGeneral.LoadDDS((MemoryStream)imageStream, (DDS_Header)header, maxDimension, formatDetails); } break; case ImageEngineFormat.DDS_G8_L8: case ImageEngineFormat.DDS_ARGB_4: case ImageEngineFormat.DDS_RGB_8: case ImageEngineFormat.DDS_V8U8: case ImageEngineFormat.DDS_A8L8: case ImageEngineFormat.DDS_ARGB_8: case ImageEngineFormat.DDS_ARGB_32F: case ImageEngineFormat.DDS_ABGR_8: case ImageEngineFormat.DDS_G16_R16: case ImageEngineFormat.DDS_R5G6B5: case ImageEngineFormat.DDS_ATI1: case ImageEngineFormat.DDS_ATI2_3Dc: case ImageEngineFormat.DDS_CUSTOM: case ImageEngineFormat.DDS_DX10: MipMaps = DDSGeneral.LoadDDS((MemoryStream)imageStream, (DDS_Header)header, maxDimension, formatDetails); break; case ImageEngineFormat.GIF: case ImageEngineFormat.JPG: case ImageEngineFormat.PNG: case ImageEngineFormat.BMP: case ImageEngineFormat.TIF: MipMaps = WIC_Codecs.LoadWithCodecs(imageStream, decodeWidth, decodeHeight, scale, false, formatDetails); break; case ImageEngineFormat.TGA: using (var tga = new TargaImage(imageStream, ((TGA_Header)header).header)) MipMaps = new List <MipMap>() { new MipMap(tga.ImageData, tga.Header.Width, tga.Header.Height, formatDetails) }; break; default: throw new FormatException($"Format unknown: {header.Format}."); } return(MipMaps); }