public int LoadFromStream(Stream stream) { if (stream == null) { return(0); } ImageImporter imageImporter = new ImageImporter(); Image image = imageImporter.LoadImageFromStream(stream); GCHandle imageDataGCHandle = GCHandle.Alloc(image.GetImageData(0).Data, GCHandleType.Pinned); IntPtr imageDataIntPtr = imageDataGCHandle.AddrOfPinnedObject(); int glTextureHandle = GL.GenTexture(); GL.Enable(EnableCap.Texture2D); GL.BindTexture(TextureTarget.Texture2D, glTextureHandle); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba8, image.Width, image.Height, 0, PixelFormat.Rgba, PixelType.UnsignedByte, imageDataIntPtr); GL.BindTexture(TextureTarget.Texture2D, 0); GL.Disable(EnableCap.Texture2D); imageDataGCHandle.Free(); textures.Add(glTextureHandle); return(glTextureHandle); }
public StockDetailsViewModel() { if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject())) { return; } try { ImgImp = new ImageImporter(); if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject())) { return; } StockObj = ObjectMessenger.FindObject("SelectedStockItem"); StockObj.UpdateCurrentObject(); StockHistory = new ObservableCollection <skStockHistory>(StockObj.StockHistory.GetStockHistory(StockObj.Stockid)); ImageLIst = new ObservableCollection <string>(); _UpdateStock = new Command(BasicStockUpdate); _UploadPhotos = new Command(PhotoUpload); _OpenTransactionDetails = new Command(OpenTransactionObject); _Loaded = new AsynchronousCommand(Load); _SubmitPurchaseLinkCommand = new Command(SubmitPurchaseLinkMethod); ObjectSourceList = new ObservableCollection <Data.Interfaces.ITransaction>(skPurchase.GetPurchases()); _LinkPurchaseCommand = new Command(LinkPurchaseMethod); FillComboBoxes(); } catch (Exception E) { ExepionLogger.Logger.LogException(E); ExepionLogger.Logger.Show(E); } }
static public Texture LoadFromFile(string filePath) { ImageImporter importer = new ImageImporter(); ImageExporter exporter = new ImageExporter(); Image image; image = importer.LoadImage(filePath); if (Path.GetExtension(filePath) != ".tga" && Path.GetExtension(filePath) != ".png") { if (!File.Exists(filePath.Replace(Path.GetExtension(filePath), ".tga"))) { exporter.SaveImage(image, ImageType.Tga, filePath.Replace(Path.GetExtension(filePath), ".tga")); } image = importer.LoadImage(filePath.Replace(Path.GetExtension(filePath), ".tga")); } //image.Bind(); //var info = DevIL.Unmanaged.IL.GetImageInfo(); //var bitmap = new System.Drawing.Bitmap(info.Width, info.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //var rect = new System.Drawing.Rectangle(0, 0, info.Width, info.Height); //var data = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //DevIL.Unmanaged.IL.CopyPixels(0, 0, 0, info.Width, info.Height, info.Depth, DataFormat.BGRA, DataType.UnsignedByte); //bitmap.UnlockBits(data); //var converter = new System.Drawing.ImageConverter(); //var test = converter.ConvertTo(bitmap, typeof(byte[])); //var raw = (byte[])converter.ConvertTo(bitmap, typeof(byte[])); return(new Texture(image)); }
public DevILTranslator() { m_importer = new ImageImporter(); m_imageState = new ImageState(); m_compState = new CompressionState(); m_compState.KeepDxtcData = true; }
private void importImageCommand(CommandLineApplication command) { var eventIdOption = command.Option("-eventId", "Event Id", CommandOptionType.SingleValue); var imagePathOption = command.Option("-imagePath", "ImagePath", CommandOptionType.SingleValue); var purposeOption = command.Option("-purpose", "Banner or Poster", CommandOptionType.SingleValue); command.OnExecute(() => { var importer = new ImageImporter(_imageService, _eventService); ImageImporter.PurposeEnum purpose = ImageImporter.PurposeEnum.Banner; Guid eventId = Guid.Empty; if (!Enum.TryParse(purposeOption.Value(), out purpose) || !Guid.TryParse(eventIdOption.Value(), out eventId)) { Console.WriteLine("Invalid value for -purpose or -eventId"); return(-1); } try { importer.ImportImageAsync(eventId, imagePathOption.Value(), purpose).Wait(); } catch (Exception e) { Console.WriteLine(e.Message); return(-1); } return(0); }); }
private void setTagsCommand(CommandLineApplication command) { var eventIdOption = command.Option("-eventId", "Event Id", CommandOptionType.SingleValue); var tags = command.Option("-tags", "Tags (Comma-Delimited)", CommandOptionType.SingleValue); command.OnExecute(() => { var importer = new ImageImporter(_imageService, _eventService); Guid eventId = Guid.Empty; if (!Guid.TryParse(eventIdOption.Value(), out eventId)) { command.Out.WriteLine("Invalid value for -purpose or -eventId"); return(-1); } var @event = _eventService.FindOneAsync(eventId).Result; if (@event == null) { command.Out.WriteLine($"Event {eventId} not found."); return(-1); } @event.Tags = tags.Value().Split(','); @event.Touch(); _eventService.ReplaceOneAsync(@event).Wait(); command.Out.WriteLine($"Event {eventId} ({@event.Title} - {@event.SubTitle}) updated with tags: {String.Join(", ", @event.Tags)}"); return(0); }); }
private void _loadBitmap(uint sideID) { // Import the image ImageImporter _importer = new ImageImporter(); _images[sideID] = _importer.LoadImage(_textures[sideID]); // Dispose the importer _importer.Dispose(); // Bind the impi]orted Image _images[sideID].Bind(); // Generate bitmap from image Bitmap BitmapImage = _images[sideID].ToBitmap(); // Must be Format32bppArgb file format, so convert it if it isn't in that format BitmapData bitmapData = BitmapImage.LockBits(new System.Drawing.Rectangle(0, 0, BitmapImage.Width, BitmapImage.Height), ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); GL.TexImage2D(_types[sideID], 0, PixelInternalFormat.Rgba8, BitmapImage.Width, BitmapImage.Height, 0, Core.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, bitmapData.Scan0); GL.TexParameteri(TextureTarget.TextureCubeMap, TextureParameterName.TextureMagFilter, TextureParameter.Linear); GL.TexParameteri(TextureTarget.TextureCubeMap, TextureParameterName.TextureMinFilter, TextureParameter.Linear); GL.TexParameteri(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapS, TextureParameter.ClampToEdge); GL.TexParameteri(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapT, TextureParameter.ClampToEdge); GL.TexParameteri(TextureTarget.TextureCubeMap, TextureParameterName.TextureWrapR, TextureParameter.ClampToEdge); // Dispose bitmap (it will not longer be used) BitmapImage.UnlockBits(bitmapData); BitmapImage.Dispose(); // Make sure the Image will not be modified from the outside _images[sideID].Unbind(); }
private void ImageImporterToolStripMenuItem_Click(object sender, EventArgs e) { if (selectedModViewer.IsVanilla) { return; } ImageImporter ii = new ImageImporter(); if (ii.ShowDialog() == DialogResult.OK) { switch (ii.DisplayedImageType.ToLower()) { case "aspect": File.Copy(ii.DisplayedImagePath, selectedModViewer.Content.CurrentDirectory + "\\images\\aspects\\" + ii.DisplayedFileName, true); break; case "element": File.Copy(ii.DisplayedImagePath, selectedModViewer.Content.CurrentDirectory + "\\images\\elements\\" + ii.DisplayedFileName, true); break; case "ending": File.Copy(ii.DisplayedImagePath, selectedModViewer.Content.CurrentDirectory + "\\images\\endings\\" + ii.DisplayedFileName, true); break; case "legacy": File.Copy(ii.DisplayedImagePath, selectedModViewer.Content.CurrentDirectory + "\\images\\legacies\\" + ii.DisplayedFileName, true); break; case "verb": File.Copy(ii.DisplayedImagePath, selectedModViewer.Content.CurrentDirectory + "\\images\\verbs\\" + ii.DisplayedFileName, true); break; } MessageBox.Show("Imported " + ii.DisplayedImageType + " image."); } }
public void Start() { //Load Contact Data _imageImporter = new ImageImporter(); _images = _imageImporter.GetList(); _currentIndex = 0; LoadContent(); }
public MainWindowVM() : base() { MainTabControlVM = mainTabVM = new MainTabControlVM(); MainTabControlVM.Items = new ObservableCollection <ImageControlVM>(); ImageImporter i = new ImageImporter(); foreach (string s in i.GetFiles()) { MainTabControlVM.Items.Add(new ImageControlVM(s)); } }
public List<Bitmap> LoadImageFiles(string[] fileNames, Action<int> onProgressChangedCallback) { var images = new List<Bitmap>(); int progress = 0; Parallel.ForEach(fileNames, fileName => { IGenericResourceImporter<Tuple<Size, ScalingMode>, Bitmap> importer = new ImageImporter(); importer.ImportParameters = new Tuple<Size, ScalingMode>(AppModel.Instance.Layout.MaximumSize(), ScalingMode.CustomSize); Bitmap image = importer.Acquire(fileName); images.Add(image); onProgressChangedCallback(Interlocked.Increment(ref progress)); }); return images; }
public static System.Drawing.Image LoadDrawingImageFromStream(Stream stream) { ImageImporter importer = new ImageImporter(); Image img = importer.LoadImageFromStream(stream); DevIL.Unmanaged.ImageInfo data = img.GetImageInfo(); SD.Bitmap bitmap = new SD.Bitmap(data.Width, data.Height, SDI.PixelFormat.Format32bppArgb); SD.Rectangle rect = new SD.Rectangle(0, 0, data.Width, data.Height); SDI.BitmapData bdata = bitmap.LockBits(rect, SDI.ImageLockMode.WriteOnly, SDI.PixelFormat.Format32bppArgb); DevIL.Unmanaged.IL.CopyPixels(0, 0, 0, data.Width, data.Height, 1, DataFormat.BGRA, DevIL.DataType.UnsignedByte, bdata.Scan0); bitmap.UnlockBits(bdata); return((SD.Image)bitmap); }
/// <summary> /// Load an image and use it as a cursor. /// </summary> /// <param name="image">The path to the image.</param> public void FromImage(string image) { ImageImporter importer = new ImageImporter(); Image img = importer.LoadImage(image); importer.Dispose(); img.Bind(); _image.Width = img.Width; _image.Height = img.Height; _image.Pixels = IL.CopyPixels(0, 0, 0, img.Width, img.Height, 1, DataFormat.BGRA, DataType.UnsignedByte); img.Unbind(); img.Dispose(); _cursor = GLFW.GLFW.CreateCursor(_image, HotX, HotY); }
static void Main(string[] args) { if (Arguments.Parse(args, out var arguments)) { IImageImporter imageImporter = new ImageImporter(); imageImporter.ImportStarted += ImportStarted; imageImporter.FileCopied += FileCopied; imageImporter.FileFailed += FileFailed; imageImporter.ImportFinished += ImportFinished; imageImporter.Initialize( arguments.ConfigurationPath, arguments.OutputDirectory, arguments.RawFileExtensions, arguments.NonRawFileExtensions, arguments.VideoFileExtensions, string.Empty); imageImporter.Import(arguments.InputDirectory); } }
/// <summary> /// Load and create a new image. /// </summary> /// <param name="file">The image file.</param> /// <param name="offsetX">The X offset from which pixels will be read.</param> /// <param name="offsetY">The Y offset from which pixels will be read.</param> /// <param name="offsetZ">The Z offset from which pixels will be read.</param> /// <param name="width">The width of the loaded.</param> /// <param name="height">The height of the loaded.</param> /// <param name="depth">The depth.</param> /// <param name="format">The format in which pixels will be read.</param> /// <param name="type">The type of data in which pixels will be read.</param> public Image(string file, int offsetX = 0, int offsetY = 0, int offsetZ = 0, int width = 0, int height = 0, int depth = 1, DataFormat format = DataFormat.BGRA, DataType type = DataType.UnsignedByte) { ImageImporter importer = new ImageImporter(); _i = importer.LoadImage(file); // Dispose the importer importer.Dispose(); // Populate fields _x = offsetX; _y = offsetY; _z = offsetZ; _d = depth; _f = format; _t = type; // Register this resource as a disposable resource ResourcesManager.AddDisposableResource(this); }
private void InitDevIL() { m_importer = new ImageImporter(); m_exporter = new ImageExporter(); ImageState state = new ImageState(); state.AbsoluteFormat = DataFormat.BGRA; state.AbsoluteDataType = DataType.UnsignedByte; state.AbsoluteOrigin = OriginLocation.UpperLeft; state.Apply(); CompressionState comp = new CompressionState(); comp.KeepDxtcData = true; comp.Apply(); SaveState sstate = new SaveState(); sstate.OverwriteExistingFile = true; sstate.Apply(); }
static public List <Texture> LoadFromFile(string rootPath, string filePath) { ImageImporter importer = new ImageImporter(); ImageExporter exporter = new ImageExporter(); Image image; List <Texture> textures = new List <Texture>(); string[] fps = filePath.Split('*'); string fp; for (int i = 0; i < fps.Length; i++) { fp = rootPath + fps[i]; image = importer.LoadImage(fp); if (Path.GetExtension(fp) != ".tga" && Path.GetExtension(fp) != ".png") { if (!File.Exists(fp.Replace(Path.GetExtension(fp), ".tga"))) { exporter.SaveImage(image, ImageType.Tga, fp.Replace(Path.GetExtension(fp), ".tga")); } image = importer.LoadImage(fp.Replace(Path.GetExtension(fp), ".tga")); } //image.Bind(); //var info = DevIL.Unmanaged.IL.GetImageInfo(); //var bitmap = new System.Drawing.Bitmap(info.Width, info.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //var rect = new System.Drawing.Rectangle(0, 0, info.Width, info.Height); //var data = bitmap.LockBits(rect, System.Drawing.Imaging.ImageLockMode.WriteOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb); //DevIL.Unmanaged.IL.CopyPixels(0, 0, 0, info.Width, info.Height, info.Depth, DataFormat.BGRA, DataType.UnsignedByte); //bitmap.UnlockBits(data); //var converter = new System.Drawing.ImageConverter(); //var test = converter.ConvertTo(bitmap, typeof(byte[])); //var raw = (byte[])converter.ConvertTo(bitmap, typeof(byte[])); textures.Add(new Texture(image, fp)); } return(textures); }
/// <summary> /// Creates an image from the specified stream.<br/> /// Silverlight supports PNG and JPEF only. /// </summary> /// <param name="stream">The stream containing a BMP, PNG, GIF, JPEG, TIFF, or PDF file.</param> /// <param name="platformIndependent">Uses an platform-independent implementation if set to true. /// The platform-dependent implementation, if available, will support more image formats.</param> /// <param name="document">The document used to obtain the options.</param> internal static XImage FromStream(Stream stream, bool platformIndependent, PdfDocument document) { if (!platformIndependent) { return(FromStream(stream)); } // TODO: Check PDF file. ImageImporter ii = ImageImporter.GetImageImporter(); ImportedImage i = ii.ImportImage(stream, document); if (i == null) { throw new InvalidOperationException("Unsupported image format."); } XImage image = new XImage(i); image._stream = stream; return(image); }
private AbstractFileImporter GetImporter(string fileExt) { AbstractFileImporter importer = null; switch (fileExt) { case ".doc": case ".docx": importer = new WordDocImporter(_driver); break; case ".xls": case ".xlsx": case ".pdf": case ".ppt": case ".pptx": importer = new MacroableFileImporter(_driver); break; case ".jpg": case ".jpeg": case ".png": importer = new ImageImporter(_driver); break; case ".vsd": case ".vsdx": case "zip": case "rtf": case ".7z": case "csv": importer = new RegularFileImporter(_driver); break; case ".txt": importer = new TextImporter(_driver); break; } return importer; }
/// <summary> /// Exports all textures to the directory specified. /// </summary> /// <param name="dir">Directory where all textures should be extracted.</param> /// <param name="mode">Mode of extraction. Range: ".dds", ".png", ".jpg", ".tiff", ".bmp".</param> /// <returns>True if export was successful.</returns> public override bool ExportTextures(string dir, string mode) { ImageType type; switch (mode) { case ".dds": type = ImageType.Dds; break; case ".png": type = ImageType.Png; break; case ".jpg": type = ImageType.Jpg; break; case ".tiff": type = ImageType.Tiff; break; case ".bmp": type = ImageType.Bmp; break; default: if (Process.MessageShow) { MessageBox.Show("Export mode provided is not supported.", "Warning"); } else { Console.WriteLine("Export mode provided is not supported."); } return(false); } if (!Directory.Exists(dir)) { if (Process.MessageShow) { MessageBox.Show("Directory provided does not exist.", "Warning"); } else { Console.WriteLine("Directory provided does not exist."); } return(false); } try { foreach (var tpk in this.TPKBlocks.Collections) { string tpkdir = tpk.CollectionName.Substring(2, tpk.CollectionName.Length - 2); tpkdir = Path.Combine(dir, tpkdir); if (!Directory.Exists(tpkdir)) { Directory.CreateDirectory(tpkdir); } foreach (var tex in tpk.Textures) { string texdir = Path.Combine(tpkdir, tex.CollectionName); texdir += mode; var data = tex.GetDDSArray(); if (mode == ".dds") { using (var bw = new BinaryWriter(File.Open(texdir, FileMode.Create))) { bw.Write(data); } } else { using (var sr = new MemoryStream(data)) using (var im = new ImageImporter()) using (var ex = new ImageExporter()) { using (var image = im.LoadImageFromStream(sr)) { ex.SaveImage(image, type, texdir); } } } } } return(true); } catch (Exception e) { if (Process.MessageShow) { MessageBox.Show(e.Message, "Warning"); } else { Console.WriteLine($"{e.Message}"); } return(false); } }
public void ExportModelToDirectoryWithExportOptions(Model model, string directory, ModelExportOptions exportOptions) { if (model == null || directory == null || exportOptions == null) { return; } NumberFormatInfo numberFormatInfo = new NumberFormatInfo(); numberFormatInfo.NumberDecimalSeparator = "."; if (exportOptions.Package) { try { DirectoryInfo directoryInfo = Directory.CreateDirectory(directory + @"\" + Path.GetFileNameWithoutExtension(model.Name)); directory = directoryInfo.FullName; } catch (Exception) { } } if (exportOptions.Textures) { ImageImporter imageImporter = new ImageImporter(); ImageExporter imageExporter = new ImageExporter(); foreach (string textureString in model.TextureStrings) { MemoryStream textureMemoryStream = AssetManager.Instance.CreateAssetMemoryStreamByName(textureString); if (textureMemoryStream == null) { continue; } Image textureImage = imageImporter.LoadImageFromStream(textureMemoryStream); if (textureImage == null) { continue; } imageExporter.SaveImage(textureImage, exportOptions.TextureFormat.ImageType, directory + @"\" + Path.GetFileNameWithoutExtension(textureString) + @"." + exportOptions.TextureFormat.Extension); } } string path = string.Format(@"{0}\{1}.{2}", directory, Path.GetFileNameWithoutExtension(model.Name), Extension); FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write); StreamWriter streamWriter = new StreamWriter(fileStream); for (int i = 0; i < model.Meshes.Length; ++i) { Mesh mesh = model.Meshes[i]; //positions List <Vector3> positions; if (mesh.GetPositions(out positions, 0)) { foreach (Vector3 position in positions) { Vector3 scaledPosition = Vector3.Multiply(position, exportOptions.Scale); streamWriter.WriteLine("v {0} {1} {2}", scaledPosition.X.ToString(numberFormatInfo), scaledPosition.Y.ToString(numberFormatInfo), scaledPosition.Z.ToString(numberFormatInfo)); } } //texture coordinates if (exportOptions.TextureCoordinates) { Vector2[] texCoords; if (mesh.GetTexCoords(out texCoords, 0)) { foreach (Vector2 texcoord in texCoords) { streamWriter.WriteLine("vt {0} {1}", texcoord.X.ToString(numberFormatInfo), (-texcoord.Y).ToString(numberFormatInfo)); } } } //normals if (exportOptions.Normals) { Vector3[] normals; if (mesh.GetNormals(out normals, 0)) { foreach (Vector3 normal in normals) { streamWriter.WriteLine("vn {0} {1} {2}", normal.X.ToString(numberFormatInfo), normal.Y.ToString(numberFormatInfo), normal.Z.ToString(numberFormatInfo)); } } } } //faces uint vertexCount = 0; for (int i = 0; i < model.Meshes.Length; ++i) { Mesh mesh = model.Meshes[i]; streamWriter.WriteLine("g Mesh{0}", i); uint[] indices; mesh.GetIndices(out indices); for (int j = 0; j < mesh.IndexCount; j += 3) { uint index0 = indices[j + 0]; uint index1 = indices[j + 1]; uint index2 = indices[j + 2]; if (exportOptions.TextureCoordinates && exportOptions.Normals) { streamWriter.WriteLine("f {0}/{0}/{0} {1}/{1}/{1} {2}/{2}/{2}", index2, index1, index0); } else if (exportOptions.Normals) { streamWriter.WriteLine("f {0}//{0} {1}//{1} {2}//{2}", index2, index1, index0); } else if (exportOptions.TextureCoordinates) { streamWriter.WriteLine("f {0}/{0} {1}/{1} {2}/{2}", index2, index1, index0); } else { streamWriter.WriteLine("f {0} {1} {2}", index2, index1, index0); } } vertexCount += (uint)mesh.VertexCount; } streamWriter.Close(); }
/// <summary> /// Attemps to export <see cref="Texture"/> specified to the path and mode provided. /// </summary> /// <param name="key">Key of the Collection Name of the <see cref="Texture"/> to be exported.</param> /// <param name="type">Type of the key passed.</param> /// <param name="path">Path where the texture should be exported.</param> /// <param name="mode">Mode in which export the texture. Range: ".dds", ".png", ".jpg", ".tiff", ".bmp".</param> /// <param name="error">Error occured when trying to clone a texture.</param> /// <returns>True if texture export was successful, false otherwise.</returns> public override bool TryExportTexture(uint key, eKeyType type, string path, string mode, out string error) { error = null; ImageType ddstype; switch (mode) { case ".dds": ddstype = ImageType.Dds; break; case ".png": ddstype = ImageType.Png; break; case ".jpg": ddstype = ImageType.Jpg; break; case ".tiff": ddstype = ImageType.Tiff; break; case ".bmp": ddstype = ImageType.Bmp; break; default: error = $"{mode} is not a supported image type that can be exported."; return(false); } var tex = (Texture)this.FindTexture(key, type); if (tex == null) { error = $"Texture with key 0x{key:X8} does not exist."; return(false); } try { var data = tex.GetDDSArray(); if (mode == ".dds") { using (var bw = new BinaryWriter(File.Open(path, FileMode.Create))) { bw.Write(data); } } else { using (var sr = new MemoryStream(data)) using (var im = new ImageImporter()) using (var ex = new ImageExporter()) { using (var image = im.LoadImageFromStream(sr)) { ex.SaveImage(image, ddstype, path); } } } return(true); } catch (System.Exception e) { while (e.InnerException != null) { e = e.InnerException; } error = e.Message; return(false); } }
/// <summary> /// Attemps to export <see cref="Texture"/> specified to the path and mode provided. /// </summary> /// <param name="key">Key of the Collection Name of the <see cref="Texture"/> to be exported.</param> /// <param name="type">Type of the key passed.</param> /// <param name="path">Path where the texture should be exported.</param> /// <param name="mode">Mode in which export the texture. Range: ".dds", ".png", ".jpg", ".tiff", ".bmp".</param> /// <returns>True if texture export was successful, false otherwise.</returns> public override bool TryExportTexture(uint key, eKeyType type, string path, string mode) { ImageType ddstype; switch (mode) { case ".dds": ddstype = ImageType.Dds; break; case ".png": ddstype = ImageType.Png; break; case ".jpg": ddstype = ImageType.Jpg; break; case ".tiff": ddstype = ImageType.Tiff; break; case ".bmp": ddstype = ImageType.Bmp; break; default: return(false); } var tex = (Texture)this.FindTexture(key, type); if (tex == null) { return(false); } try { var data = tex.GetDDSArray(); if (mode == ".dds") { using (var bw = new BinaryWriter(File.Open(path, FileMode.Create))) { bw.Write(data); } } else { using (var sr = new MemoryStream(data)) using (var im = new ImageImporter()) using (var ex = new ImageExporter()) { using (var image = im.LoadImageFromStream(sr)) { ex.SaveImage(image, ddstype, path); } } } return(true); } catch (System.Exception) { return(false); } }
public void ExportModelToDirectoryWithExportOptions(Model model, String directory, ExportOptions exportOptions) { //TODO: Figure out what to do with non-version 4 models. if (model != null && model.Version != 4) { return; } NumberFormatInfo format = new NumberFormatInfo(); format.NumberDecimalSeparator = "."; if (exportOptions.Package) { try { DirectoryInfo directoryInfo = Directory.CreateDirectory(directory + @"\" + Path.GetFileNameWithoutExtension(model.Name)); directory = directoryInfo.FullName; } catch (Exception) { } } if (exportOptions.Textures) { ImageImporter imageImporter = new ImageImporter(); ImageExporter imageExporter = new ImageExporter(); foreach (String textureString in model.TextureStrings) { MemoryStream textureMemoryStream = AssetManager.Instance.CreateAssetMemoryStreamByName(textureString); if (textureMemoryStream == null) { continue; } Image textureImage = imageImporter.LoadImageFromStream(textureMemoryStream); if (textureImage == null) { continue; } imageExporter.SaveImage(textureImage, exportOptions.TextureFormat.ImageType, directory + @"\" + Path.GetFileNameWithoutExtension(textureString) + @"." + exportOptions.TextureFormat.Extension); } } String path = directory + @"\" + Path.GetFileNameWithoutExtension(model.Name) + ".obj"; FileStream fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Write); StreamWriter streamWriter = new StreamWriter(fileStream); for (Int32 i = 0; i < model.Meshes.Length; ++i) { Mesh mesh = model.Meshes[i]; MaterialDefinition materialDefinition = MaterialDefinitionManager.Instance.MaterialDefinitions[model.Materials[(Int32)mesh.MaterialIndex].MaterialDefinitionHash]; VertexLayout vertexLayout = MaterialDefinitionManager.Instance.VertexLayouts[materialDefinition.DrawStyles[0].VertexLayoutNameHash]; //position VertexLayout.Entry.DataTypes positionDataType; Int32 positionOffset; Int32 positionStreamIndex; vertexLayout.GetEntryInfoFromDataUsageAndUsageIndex(VertexLayout.Entry.DataUsages.Position, 0, out positionDataType, out positionStreamIndex, out positionOffset); Mesh.VertexStream positionStream = mesh.VertexStreams[positionStreamIndex]; for (Int32 j = 0; j < mesh.VertexCount; ++j) { Vector3 position = readVector3(exportOptions, positionOffset, positionStream, j); position.X *= exportOptions.Scale.X; position.Y *= exportOptions.Scale.Y; position.Z *= exportOptions.Scale.Z; streamWriter.WriteLine("v " + position.X.ToString(format) + " " + position.Y.ToString(format) + " " + position.Z.ToString(format)); } //texture coordinates if (exportOptions.TextureCoordinates) { VertexLayout.Entry.DataTypes texCoord0DataType; Int32 texCoord0Offset = 0; Int32 texCoord0StreamIndex = 0; Boolean texCoord0Present = vertexLayout.GetEntryInfoFromDataUsageAndUsageIndex(VertexLayout.Entry.DataUsages.Texcoord, 0, out texCoord0DataType, out texCoord0StreamIndex, out texCoord0Offset); if (texCoord0Present) { Mesh.VertexStream texCoord0Stream = mesh.VertexStreams[texCoord0StreamIndex]; for (Int32 j = 0; j < mesh.VertexCount; ++j) { Vector2 texCoord; switch (texCoord0DataType) { case VertexLayout.Entry.DataTypes.Float2: texCoord.X = BitConverter.ToSingle(texCoord0Stream.Data, (j * texCoord0Stream.BytesPerVertex) + 0); texCoord.Y = 1.0f - BitConverter.ToSingle(texCoord0Stream.Data, (j * texCoord0Stream.BytesPerVertex) + 4); break; case VertexLayout.Entry.DataTypes.float16_2: texCoord.X = Half.FromBytes(texCoord0Stream.Data, (j * texCoord0Stream.BytesPerVertex) + texCoord0Offset + 0).ToSingle(); texCoord.Y = 1.0f - Half.FromBytes(texCoord0Stream.Data, (j * texCoord0Stream.BytesPerVertex) + texCoord0Offset + 2).ToSingle(); break; default: texCoord.X = 0; texCoord.Y = 0; break; } streamWriter.WriteLine("vt " + texCoord.X.ToString(format) + " " + texCoord.Y.ToString(format)); } } } } //faces UInt32 vertexCount = 0; for (Int32 i = 0; i < model.Meshes.Length; ++i) { Mesh mesh = model.Meshes[i]; streamWriter.WriteLine("g Mesh" + i); for (Int32 j = 0; j < mesh.IndexCount; j += 3) { UInt32 index0, index1, index2; switch (mesh.IndexSize) { case 2: index0 = vertexCount + BitConverter.ToUInt16(mesh.IndexData, (j * 2) + 0) + 1; index1 = vertexCount + BitConverter.ToUInt16(mesh.IndexData, (j * 2) + 2) + 1; index2 = vertexCount + BitConverter.ToUInt16(mesh.IndexData, (j * 2) + 4) + 1; break; case 4: index0 = vertexCount + BitConverter.ToUInt32(mesh.IndexData, (j * 4) + 0) + 1; index1 = vertexCount + BitConverter.ToUInt32(mesh.IndexData, (j * 4) + 4) + 1; index2 = vertexCount + BitConverter.ToUInt32(mesh.IndexData, (j * 4) + 8) + 1; break; default: index0 = 0; index1 = 0; index2 = 0; break; } if (exportOptions.Normals && exportOptions.TextureCoordinates) { streamWriter.WriteLine("f " + index2 + "/" + index2 + "/" + index2 + " " + index1 + "/" + index1 + "/" + index1 + " " + index0 + "/" + index0 + "/" + index0); } else if (exportOptions.Normals) { streamWriter.WriteLine("f " + index2 + "//" + index2 + " " + index1 + "//" + index1 + " " + index0 + "//" + index0); } else if (exportOptions.TextureCoordinates) { streamWriter.WriteLine("f " + index2 + "/" + index2 + " " + index1 + "/" + index1 + " " + index0 + "/" + index0); } else { streamWriter.WriteLine("f " + index2 + " " + index1 + " " + index0); } } vertexCount += (UInt32)mesh.VertexCount; } streamWriter.Close(); }