Пример #1
0
        /// <summary>
        /// Performs a no-caching load of the texture. This will always go to disk to access a file and
        /// will always return a unique Texture2D. This should not be used in most cases, as caching is preferred
        /// </summary>
        /// <param name="fileName">The filename to load</param>
        /// <param name="managers">The optional SystemManagers to use when loading the file to obtain a GraphicsDevice</param>
        /// <returns>The loaded Texture2D</returns>
        public Texture2D LoadTextureFromFile(string fileName, SystemManagers managers = null)
        {
            string fileNameStandardized = FileManager.Standardize(fileName, false, false);

            if (FileManager.IsRelative(fileNameStandardized))
            {
                fileNameStandardized = FileManager.RelativeDirectory + fileNameStandardized;

                fileNameStandardized = FileManager.RemoveDotDotSlash(fileNameStandardized);
            }

            Texture2D toReturn;
            string    extension = FileManager.GetExtension(fileName);
            Renderer  renderer  = null;

            if (managers == null)
            {
                renderer = Renderer.Self;
            }
            else
            {
                renderer = managers.Renderer;
            }
            if (extension == "tga")
            {
#if RENDERING_LIB_SUPPORTS_TGA
                if (renderer.GraphicsDevice == null)
                {
                    throw new Exception("The renderer is null - did you forget to call Initialize?");
                }

                Paloma.TargaImage tgaImage = new Paloma.TargaImage(fileName);
                using (MemoryStream stream = new MemoryStream())
                {
                    tgaImage.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                    stream.Seek(0, SeekOrigin.Begin);     //must do this, or error is thrown in next line
                    toReturn      = Texture2D.FromStream(renderer.GraphicsDevice, stream);
                    toReturn.Name = fileName;
                }
#else
                throw new NotImplementedException();
#endif
            }
            else
            {
                using (var stream = FileManager.GetStreamForFile(fileNameStandardized))
                {
                    Texture2D texture = null;

                    texture = Texture2D.FromStream(renderer.GraphicsDevice,
                                                   stream);

                    texture.Name = fileNameStandardized;

                    toReturn = texture;
                }
            }

            return(toReturn);
        }
Пример #2
0
        public Image(string file)
        {
            try
            {
                if (System.IO.File.Exists(file) == false)
                {
                    System.Diagnostics.Trace.TraceError("Error: File does not exist " + file);
                    MakeFallback();
                }

                if (file.EndsWith(".tga"))
                {
                    using (Paloma.TargaImage targa = new Paloma.TargaImage(file))
                    {
                        var bitmap = targa.Image;
                        UpdatePixels(bitmap);
                        targa.ClearAll();
                        targa.Dispose();
                    }
                }
                else
                {
                    var bitmap = new Bitmap(file);
                    UpdatePixels(bitmap);
                }
            }
            catch (System.Exception)
            {
                System.Diagnostics.Trace.TraceError("Error: Could not load " + file);
                MakeFallback();
            }
        }
Пример #3
0
 public int TargaImage()
 {
     using (var image = new Paloma.TargaImage(new MemoryStream(data)))
     {
         return(image.Stride);
     }
 }
Пример #4
0
        /// <summary>
        /// TGA转Image
        /// </summary>
        /// <param name="tgaFilename">TGA完整文件名</param>
        /// <returns>Image</returns>
        public static Image tga2img(string tgaFilename)
        {
            Paloma.TargaImage tgaImage = new Paloma.TargaImage(tgaFilename);
            return(tgaImage.Image);

            //// 读取TGA文件,分析出长宽
            //BinaryReader b = new BinaryReader(File.Open(tgaFilename, FileMode.Open));
            //b.BaseStream.Seek(0x0C, System.IO.SeekOrigin.Begin);
            //int nWidth = b.ReadInt16();
            //int nHeight = b.ReadInt16();
            //b.Close();

            //// 送tgaPreview输出jpg文件
            //string tempFilePath = Path.GetTempFileName();

            //Panel panel = new Panel();
            //tgaPreview.Init(panel.Handle);
            //tgaPreview.SetFileNames(panel.Handle, tgaFilename + "\r\n", (UInt16)nWidth, (UInt16)nHeight);
            //tgaPreview.Render(panel.Handle);
            //tgaPreview.FrameMove(panel.Handle);
            //tgaPreview.ExportToFile(panel.Handle, (UInt16)nWidth, (UInt16)nHeight, tempFilePath);
            //tgaPreview.UnInit(panel.Handle);

            //// 载入jpg文件
            //FileStream fs = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read);
            //int byteLength = (int)fs.Length;
            //byte[] wf = new byte[byteLength];
            //fs.Read(wf, 0, byteLength);
            //fs.Close();
            //Image img = Image.FromStream(new MemoryStream(wf));
            //File.Delete(tempFilePath);

            //return img;
        }
 /// <summary>
 /// Gets the thumbnail image.
 /// </summary>
 /// <param name="width">The width.</param>
 /// <returns>Bitmap.</returns>
 protected override Bitmap GetThumbnailImage(uint width)
 {
     Bitmap bmp = null;
     using (SelectedItemStream)
     {
         try
         {
             var tga = new Paloma.TargaImage(SelectedItemStream);
             if (tga != null)
             {
                 var tgaImg = tga.Image;
                 if (tgaImg != null)
                     bmp = ResizeImage(tgaImg, Convert.ToInt32(width));
                 tga.Dispose();
             }
         }
         catch (Exception ex)
         {
             LogError("TGAThumbnailViewer", ex);
         }
     }
     if (bmp == null)
         bmp = CreateEmptyBitmap(Convert.ToInt32(width));
     GC.Collect();
     return bmp;
 }
Пример #6
0
 public override Image Load(Stream s)
 {
     Paloma.TargaImage t = new Paloma.TargaImage(s);
     Image i = (Image)t.Image;
     t.Dispose();
     return i;
 }
Пример #7
0
        public void LoadPicture(string strFile)
        {
            Image    image = null;
            FileInfo fiJpg = new FileInfo(strFile);

            if (fiJpg.Exists)
            {
                if (fiJpg.Extension.ToLower() == ".tga")
                {
                    Paloma.TargaImage tgaImage = new Paloma.TargaImage(strFile);
                    image = tgaImage.Image;
                }
                else if (fiJpg.Extension.ToLower() == ".jpg")
                {
                    image = Image.FromFile(strFile);
                }
                else
                {
                    MessageBox.Show("不支持这种图片格式in LoadPicture。");
                }

                panel1.PaintPicture(image);
                panel1.ClearPaint();
                m_image = image;
                panel1_SizeChanged(null, null);
            }
        }
Пример #8
0
        public override Image Load(Stream s)
        {
            Paloma.TargaImage t = new Paloma.TargaImage(s);
            Image             i = (Image)t.Image;

            t.Dispose();
            return(i);
        }
Пример #9
0
 public void LoadPicture(string strFile)
 {
     Paloma.TargaImage tgaImage = new Paloma.TargaImage(strFile);
     Image image = tgaImage.Image;
     panel1.PaintPicture(image);
     panel1.ClearPaint();
     m_image = image;
     panel1_SizeChanged(null, null);
 }
Пример #10
0
        public void LoadPicture(string strFile)
        {
            Paloma.TargaImage tgaImage = new Paloma.TargaImage(strFile);
            Image             image    = tgaImage.Image;

            panel1.PaintPicture(image);
            panel1.ClearPaint();
            m_image = image;
            panel1_SizeChanged(null, null);
        }
Пример #11
0
        public async Task <ActionResult <object> > PostImg()
        {
            string root = "tga/";

            if (!Directory.Exists(root))
            {
                Directory.CreateDirectory(root);
            }
            TGAcontainer containerTemp = new TGAcontainer();

            containerTemp.IPaddress = Request.HttpContext.Connection.RemoteIpAddress.ToString();
            ImgUpload temp = new ImgUpload();

            Request.Headers["filename"] = Regex.Replace(Request.Headers["filename"], "[^a-zA-Z0-9% ._]", string.Empty);
            containerTemp.filename      = Request.Headers["filename"] + ".tga";
            containerTemp.originalImg   = root + DateTime.Now.ToString("dd-MM-yyyy-hh_mm-ss-ffff") + "_" + Request.Headers["filename"] + ".tga";
            temp.FileName = containerTemp.filename;
            using (var fs = new FileStream("wwwroot/" + containerTemp.originalImg, FileMode.Create))
            {
                Request.Body.CopyTo(fs);
            }

            try
            {
                var extension       = ImageExtensions.GetImageFormat(Request.Headers["extension"]);
                var stringExtension = Request.Headers["extension"];
                var image           = new Paloma.TargaImage("wwwroot/" + containerTemp.originalImg);
                containerTemp.version = image.Format;
                Bitmap convertedImage = new Bitmap(image.Image);
                image.Dispose();

                using (var bitmap = new Bitmap(convertedImage))
                {
                    string filename = root + DateTime.Now.ToString("dd-MM-yyyy-hh-mm-ss-ffff") + "_" + Request.Headers["filename"] + stringExtension;
                    bitmap.Save("wwwroot/" + filename, extension);
                    containerTemp.convertedImg = filename;
                }
                containerTemp.dateTime       = DateTime.Now;
                containerTemp.downloadFormat = stringExtension;
                containerTemp.height         = convertedImage.Height;
                containerTemp.width          = convertedImage.Width;
                convertedImage.Dispose();
                _context.TGAcontainers.RemoveRange(_context.TGAcontainers.OrderBy(x => x.dateTime).Take(_context.TGAcontainers.Count() - 4));
                _context.TGAcontainers.Add(containerTemp);
                await _context.SaveChangesAsync();

                temp.id = _context.TGAcontainers.Last().id;
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e.Message);
                return(NotFound());
            }
            return(temp);
        }
Пример #12
0
 /// <summary>
 /// Loads a texture from the specified path.
 /// </summary>
 /// <param name="Path">The path from which to load a texture.</param>
 /// <returns>A Texture2D instance.</returns>
 private Texture2D LoadTexture(string Path)
 {
     if (Path.Contains(".tga"))
     {
         MemoryStream      Png = new MemoryStream();
         Paloma.TargaImage TGA = new Paloma.TargaImage(new FileStream(Path, FileMode.Open, FileAccess.Read));
         TGA.Image.Save(Png, ImageFormat.Png);
         Png.Position = 0;
         return(Texture2D.FromStream(m_Device, Png));
     }
     else
     {
         return(Texture2D.FromStream(m_Device, new FileStream(Path, FileMode.Open, FileAccess.Read)));
     }
 }
Пример #13
0
        public static Texture2D FromStream(GraphicsDevice gd, Stream str)
        {
            try
            {
                return Texture2D.FromStream(gd, str);
            }
            catch (Exception)
            {
                try
                {
                    bool premultiplied = false;
                    Bitmap bmp = null;
                    try {
                        bmp = (Bitmap)Image.FromStream(str); //try as bmp
                    } catch (Exception) {
                        str.Seek(0, SeekOrigin.Begin);
                        var tga = new Paloma.TargaImage(str);
                        bmp = tga.Image; //try as tga. for some reason this format does not have a magic number, which is ridiculously stupid.
                    }

                    var data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    var bytes = new byte[data.Height * data.Stride];

                    // copy the bytes from bitmap to array
                    Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

                    for (int i = 0; i < bytes.Length; i += 4)
                    { //flip red and blue and premultiply alpha
                        byte temp = bytes[i + 2];
                        float a = (premultiplied) ? 1 : (bytes[i + 3] / 255f);
                        bytes[i + 2] = (byte)(bytes[i] * a);
                        bytes[i + 1] = (byte)(bytes[i + 1] * a);
                        bytes[i] = (byte)(temp * a);
                    }

                    var tex = new Texture2D(gd, data.Width, data.Height);
                    tex.SetData<byte>(bytes);
                    return tex;
                }
                catch (Exception)
                {
                    return null;
                }
            }
        }
Пример #14
0
        public static Bitmap FromStream(Stream str)
        {
            try
            {
                bool   premultiplied = false;
                Bitmap bmp           = null;
                try
                {
                    bmp = (Bitmap)Image.FromStream(str);                     //try as bmp
                }
                catch (Exception)
                {
                    str.Seek(0, SeekOrigin.Begin);
                    var tga = new Paloma.TargaImage(str);
                    bmp = tga.Image;                     //try as tga. for some reason this format does not have a magic number, which is ridiculously stupid.
                }

                var data  = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                var bytes = new byte[data.Height * data.Stride];

                // copy the bytes from bitmap to array
                Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

                for (int i = 0; i < bytes.Length; i += 4)
                {                 //flip red and blue and premultiply alpha
                    byte  temp = bytes[i + 2];
                    float a    = (premultiplied) ? 1 : (bytes[i + 3] / 255f);
                    bytes[i + 2] = (byte)(bytes[i] * a);
                    bytes[i + 1] = (byte)(bytes[i + 1] * a);
                    bytes[i]     = (byte)(temp * a);
                }

                Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);                 //copy modified bits back
                bmp.UnlockBits(data);

                return(bmp);
            }
            catch (Exception e)
            {
                return(null);
            }
        }
Пример #15
0
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            m_Effect = Content.Load <Effect>("VTFDisplacement");

            m_Heightmap = Texture2D.FromStream(graphics.GraphicsDevice,
                                               File.Open(GlobalSettings.Default.StartupPath + "cities\\city_0026\\elevation.bmp",
                                                         FileMode.Open, FileAccess.Read, FileShare.ReadWrite));

            Paloma.TargaImage TImg = new Paloma.TargaImage(File.Open(GlobalSettings.Default.StartupPath +
                                                                     "gamedata\\terrain\\newformat\\sd.tga", FileMode.Open, FileAccess.ReadWrite));
            MemoryStream ImgStream = new MemoryStream();

            TImg.Image.Save(ImgStream, ImageFormat.Bmp);

            m_SandTex = Texture2D.FromStream(graphics.GraphicsDevice, ImgStream);

            TImg = new Paloma.TargaImage(File.Open(GlobalSettings.Default.StartupPath +
                                                   "gamedata\\terrain\\newformat\\gr.tga", FileMode.Open, FileAccess.ReadWrite));
            ImgStream = new MemoryStream();
            TImg.Image.Save(ImgStream, ImageFormat.Bmp);

            m_GrassTex = Texture2D.FromStream(graphics.GraphicsDevice, ImgStream);

            TImg = new Paloma.TargaImage(File.Open(GlobalSettings.Default.StartupPath +
                                                   "gamedata\\terrain\\newformat\\rk.tga", FileMode.Open, FileAccess.ReadWrite));
            ImgStream = new MemoryStream();
            TImg.Image.Save(ImgStream, ImageFormat.Bmp);

            m_RockTex = Texture2D.FromStream(graphics.GraphicsDevice, ImgStream);

            TImg = new Paloma.TargaImage(File.Open(GlobalSettings.Default.StartupPath +
                                                   "gamedata\\terrain\\newformat\\sn.tga", FileMode.Open, FileAccess.ReadWrite));
            ImgStream = new MemoryStream();
            TImg.Image.Save(ImgStream, ImageFormat.Bmp);

            m_SnowTex = Texture2D.FromStream(graphics.GraphicsDevice, ImgStream);

            m_Grid.LoadGraphicsContent();
        }
Пример #16
0
        private void SheetImport_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog
            {
                Filter = "TGA Sprite Sheets (select non Alpha)|*.tga"
            };

            if (FileBrowse(dialog))
            {
                try
                {
                    var name = dialog.FileName;
                    var tga1 = new Paloma.TargaImage(name).Image;
                    var tga2 = new Paloma.TargaImage(name.Substring(0, name.Length - 4) + "Alpha.tga").Image;

                    if (tga1.Width % 238 != 0)
                    {
                        MessageBox.Show("Invalid sheet!");
                    }

                    var rotations = tga1.Width / 238;

                    for (int r = 0; r < rotations; r++)
                    {
                        ReplaceSprite(ChannelFromSlice(tga1, tga2, new Rectangle(r * 136, 0, 136, 384)), r + 0 * (GraphicChunk.Frames.Length / 3));
                        ReplaceSprite(ChannelFromSlice(tga1, tga2, new Rectangle(r * 68 + rotations * 136, 0, 68, 192)), r + 1 * (GraphicChunk.Frames.Length / 3));
                        ReplaceSprite(ChannelFromSlice(tga1, tga2, new Rectangle(r * 34 + rotations * (136 + 68), 0, 34, 96)), r + 2 * (GraphicChunk.Frames.Length / 3));
                    }

                    var stream = new MemoryStream();
                    GraphicChunk.Write(GraphicChunk.ChunkParent, stream);
                    GraphicChunk.ChunkData      = stream.ToArray();
                    GraphicChunk.ChunkProcessed = false;
                    GraphicChunk.Dispose();
                    GraphicChunk.ChunkParent.Get <SPR2>(GraphicChunk.ChunkID);
                    UpdateGraphics();
                }
                catch (Exception ex) {
                    MessageBox.Show("Failed to import TGAs! Make sure ...Alpha.tga is also present.");
                }
            }
        }
Пример #17
0
        private void setImage(string imagePath)
        {
            if (pictureBox1.Image != null)
            {
                pictureBox1.Image.Dispose();
                pictureBox1.Image = null;
            }

            provinces.Clear();

            if (System.IO.File.Exists(imagePath))
            {
                using (var tgaImage = new Paloma.TargaImage(imagePath))
                {
                    layeredImage.BackgroundImage = tgaImage.Image;
                }

                updateImage();
            }
        }
Пример #18
0
        public static string GetRTFFromTgaFile(string strFileName, Control CurControl, int nFrame)
        {
            int    nIndexPos  = strFileName.LastIndexOf(".");
            string ExpandName = strFileName.Substring(nIndexPos, strFileName.Length - nIndexPos).ToLower();

            Image _image;

            if (ExpandName == ".uitex")
            {
                int nFileNamePos = strFileName.LastIndexOf("\\");
                _image = uitex2img(strFileName.Substring(0, nFileNamePos), strFileName, nFrame);
            }
            else if (ExpandName == ".tga")
            {
                Paloma.TargaImage tgaImage = new Paloma.TargaImage(strFileName);
                _image = tgaImage.Image;
            }
            else
            {
                MessageBox.Show("错误的文件扩展名。");
                return(string.Empty);
            }

            StringBuilder _rtf = new StringBuilder();

            using (Graphics _graphics = CurControl.CreateGraphics())
            {
                xDpi = _graphics.DpiX;
                yDpi = _graphics.DpiY;
            }
            _rtf.Append(RTF_HEADER);
            _rtf.Append(GetFontTable());
            _rtf.Append(GetImagePrefix(_image));
            _rtf.Append(GetRtfImage(_image, CurControl));
            _rtf.Append(RTF_IMAGE_POST);

            return(_rtf.ToString());
        }
Пример #19
0
        private bool _convertStill(Media localSourceMedia)
        {
            CreateDestMediaIfNotExists();
            Media destMedia = DestMedia as Media;

            if (destMedia != null)
            {
                destMedia.MediaType = TMediaType.Still;
                Size     destSize = destMedia.VideoFormat == TVideoFormat.Other ? VideoFormatDescription.Descriptions[TVideoFormat.HD1080i5000].ImageSize : destMedia.FormatDescription().ImageSize;
                Image    bmp      = new Bitmap(destSize.Width, destSize.Height, PixelFormat.Format32bppArgb);
                Graphics graphics = Graphics.FromImage(bmp);
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                if (Path.GetExtension(localSourceMedia.FileName).ToLowerInvariant() == ".tga")
                {
                    var tgaImage = new Paloma.TargaImage(localSourceMedia.FullPath);
                    graphics.DrawImage(tgaImage.Image, 0, 0, destSize.Width, destSize.Height);
                }
                else
                {
                    graphics.DrawImage(new Bitmap(localSourceMedia.FullPath), 0, 0, destSize.Width, destSize.Height);
                }
                ImageCodecInfo imageCodecInfo          = ImageCodecInfo.GetImageEncoders().FirstOrDefault(e => e.FilenameExtension.Split(';').Select(se => se.Trim('*')).Contains(FileUtils.DefaultFileExtension(TMediaType.Still).ToUpperInvariant()));
                System.Drawing.Imaging.Encoder encoder = System.Drawing.Imaging.Encoder.Quality;
                EncoderParameter  encoderParameter     = new EncoderParameter(encoder, 90L);
                EncoderParameters encoderParameters    = new EncoderParameters(1);
                encoderParameters.Param[0] = encoderParameter;
                bmp.Save(destMedia.FullPath, imageCodecInfo, encoderParameters);
                destMedia.MediaStatus = TMediaStatus.Copied;
                ((Media)destMedia).Verify();
                OperationStatus = FileOperationStatus.Finished;
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #20
0
        public void LoadPicture(string strFile)
        {
            Image image = null;
            FileInfo fiJpg = new FileInfo(strFile);
            if (fiJpg.Exists)
            {
                if (fiJpg.Extension.ToLower() == ".tga")
                {
                    Paloma.TargaImage tgaImage = new Paloma.TargaImage(strFile);
                    image = tgaImage.Image;
                }
                else if (fiJpg.Extension.ToLower() == ".jpg")
                {
                    image = Image.FromFile(strFile);
                }
                else
                    MessageBox.Show("不支持这种图片格式in LoadPicture。");

                panel1.PaintPicture(image);
                panel1.ClearPaint();
                m_image = image;
                panel1_SizeChanged(null, null);
            }
        }
Пример #21
0
        public static Texture2D FromStream(GraphicsDevice gd, Stream str)
        {
            //test for bmp
            Bitmap bmp   = null;
            var    magic = (str.ReadByte() | (str.ReadByte() << 8));

            str.Seek(0, SeekOrigin.Begin);
            if (magic == 0x4D42)
            {
                try
                {
                    bmp = (Bitmap)Image.FromStream(str); //try as bmp
                }
                catch (Exception)
                {
                    return(null); //bad bitmap
                }
            }
            else
            {
                //test for targa
                str.Seek(-18, SeekOrigin.End);
                byte[] sig = new byte[16];
                str.Read(sig, 0, 16);
                str.Seek(0, SeekOrigin.Begin);
                if (ASCIIEncoding.Default.GetString(sig) == "TRUEVISION-XFILE")
                {
                    try
                    {
                        bmp = new Paloma.TargaImage(str).Image; //try as tga
                    }
                    catch (Exception)
                    {
                        return(null); //bad tga
                    }
                }
            }

            if (bmp != null)
            {
                //image loaded into bitmap
                bool premultiplied = false;

                var data  = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                var bytes = new byte[data.Height * data.Stride];

                // copy the bytes from bitmap to array
                Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);

                for (int i = 0; i < bytes.Length; i += 4)
                { //flip red and blue and premultiply alpha
                    if (bytes[i] > 0xFD && bytes[i + 1] < 3 && bytes[i + 2] > 0xFD)
                    {
                        bytes[i + 3] = 0;
                    }
                    byte  temp = bytes[i + 2];
                    float a    = (premultiplied) ? 1 : (bytes[i + 3] / 255f);
                    bytes[i + 2] = (byte)(bytes[i] * a);
                    bytes[i + 1] = (byte)(bytes[i + 1] * a);
                    bytes[i]     = (byte)(temp * a);
                }

                var tex = new Texture2D(gd, data.Width, data.Height);
                tex.SetData <byte>(bytes);
                return(tex);
            }
            else
            {
                //attempt monogame load of image
                try {
                    return(Texture2D.FromStream(gd, str));
                }
                catch (Exception)
                {
                    return(null);
                }
            }
        }
Пример #22
0
        private MemoryStream LoadAsPNG(Stream strm, out int Width, out int Height)
        {
            MemoryStream ms = null;

            try
            {
                // attempt loading the image stream with standard .NET

                strm.Seek(0, System.IO.SeekOrigin.Begin);

                Bitmap vBitmap = new Bitmap(strm);
                Width = vBitmap.Width;
                Height = vBitmap.Height;

                ms = new MemoryStream();
                vBitmap.Save(ms, ImageFormat.Png);
            }
            catch
            {
                // incase of an exception the image stream may not be a validly .NET supported format
                // lets try Targa (TGA), maybe we'll get lucky

                strm.Seek(0, System.IO.SeekOrigin.Begin);

                Paloma.TargaImage vTargaImage = new Paloma.TargaImage(strm);

                Width = vTargaImage.Image.Width;
                Height = vTargaImage.Image.Height;

                ms = new MemoryStream();
                vTargaImage.Image.Save(ms, ImageFormat.Png);
            }

            return ms;
        }
Пример #23
0
        public static Texture2D LoadFromTgaFile(Device device, string filename)
        {
            var tga = new Paloma.TargaImage(filename);

            return(Load(device, tga.Image));
        }
Пример #24
0
        public static string GetRTFFromTgaFile(string strFileName, Control CurControl, int nFrame)
        {
            int nIndexPos = strFileName.LastIndexOf(".");
            string ExpandName = strFileName.Substring(nIndexPos, strFileName.Length - nIndexPos).ToLower() ;

            Image _image;
            if (ExpandName == ".uitex")
            {
                int nFileNamePos = strFileName.LastIndexOf("\\");
                _image = uitex2img(strFileName.Substring(0, nFileNamePos), strFileName, nFrame);
            }
            else if (ExpandName == ".tga")
            {
                Paloma.TargaImage tgaImage = new Paloma.TargaImage(strFileName);
                _image = tgaImage.Image;
            }
            else
            {
                MessageBox.Show("错误的文件扩展名。");
                return string.Empty;
            }
            
            StringBuilder _rtf = new StringBuilder();

            using (Graphics _graphics = CurControl.CreateGraphics())
            {
                xDpi = _graphics.DpiX;
                yDpi = _graphics.DpiY;
            }
            _rtf.Append(RTF_HEADER);
            _rtf.Append(GetFontTable());
            _rtf.Append(GetImagePrefix(_image));
            _rtf.Append(GetRtfImage(_image, CurControl));
            _rtf.Append(RTF_IMAGE_POST);

            return _rtf.ToString();
        }
Пример #25
0
        private void SheetImport_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog();
            dialog.Filter = "TGA Sprite Sheets (select non Alpha)|*.tga";
            if (FileBrowse(dialog))
            {
                try
                {
                    var name = dialog.FileName;
                    var tga1 = new Paloma.TargaImage(name).Image;
                    var tga2 = new Paloma.TargaImage(name.Substring(0,name.Length-4)+"Alpha.tga").Image;

                    if (tga1.Width % 238 != 0) {
                        MessageBox.Show("Invalid sheet!");
                    }

                    var rotations = tga1.Width / 238;

                    for (int r=0; r< rotations; r++)
                    {
                        ReplaceSprite(ChannelFromSlice(tga1, tga2, new Rectangle(r * 136, 0, 136, 384)), r + 0 * (GraphicChunk.Frames.Length / 3));
                        ReplaceSprite(ChannelFromSlice(tga1, tga2, new Rectangle(r * 68 + rotations*136, 0, 68, 192)), r + 1 * (GraphicChunk.Frames.Length / 3));
                        ReplaceSprite(ChannelFromSlice(tga1, tga2, new Rectangle(r * 34 + rotations * (136 + 68), 0, 34, 96)), r + 2 * (GraphicChunk.Frames.Length / 3));
                    }

                    var stream = new MemoryStream();
                    GraphicChunk.Write(GraphicChunk.ChunkParent, stream);
                    GraphicChunk.ChunkData = stream.ToArray();
                    GraphicChunk.ChunkProcessed = false;
                    GraphicChunk.Dispose();
                    GraphicChunk.ChunkParent.Get<SPR2>(GraphicChunk.ChunkID);
                    UpdateGraphics();
                }
                catch (Exception ex) {
                    MessageBox.Show("Failed to import TGAs! Make sure ...Alpha.tga is also present.");
                }
            }
        }
Пример #26
0
        /// <summary>
        /// TGA转Image
        /// </summary>
        /// <param name="tgaFilename">TGA完整文件名</param>
        /// <returns>Image</returns>
        public static Image tga2img(string tgaFilename)
        {
            Paloma.TargaImage tgaImage = new Paloma.TargaImage(tgaFilename);
            return tgaImage.Image;

            //// 读取TGA文件,分析出长宽
            //BinaryReader b = new BinaryReader(File.Open(tgaFilename, FileMode.Open));
            //b.BaseStream.Seek(0x0C, System.IO.SeekOrigin.Begin);
            //int nWidth = b.ReadInt16();
            //int nHeight = b.ReadInt16();
            //b.Close();

            //// 送tgaPreview输出jpg文件
            //string tempFilePath = Path.GetTempFileName();

            //Panel panel = new Panel();
            //tgaPreview.Init(panel.Handle);
            //tgaPreview.SetFileNames(panel.Handle, tgaFilename + "\r\n", (UInt16)nWidth, (UInt16)nHeight);
            //tgaPreview.Render(panel.Handle);
            //tgaPreview.FrameMove(panel.Handle);
            //tgaPreview.ExportToFile(panel.Handle, (UInt16)nWidth, (UInt16)nHeight, tempFilePath);
            //tgaPreview.UnInit(panel.Handle);

            //// 载入jpg文件  
            //FileStream fs = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read);
            //int byteLength = (int)fs.Length;
            //byte[] wf = new byte[byteLength];
            //fs.Read(wf, 0, byteLength);
            //fs.Close();
            //Image img = Image.FromStream(new MemoryStream(wf));
            //File.Delete(tempFilePath);

            //return img;
        }
Пример #27
0
        public static Bitmap Load(string path)
        {
            path = path.ToLower();
            Bitmap bmp = null;

            //file *.hdr
            if (path.EndsWith(".hdr"))
            {
                FIBITMAP hdr = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_HDR, path, FREE_IMAGE_LOAD_FLAGS.RAW_DISPLAY);
                bmp = FreeImage.GetBitmap(FreeImage.ToneMapping(hdr, FREE_IMAGE_TMO.FITMO_DRAGO03, 2.2, 0));
                FreeImage.Unload(hdr);
            }
            //file *.exr
            else if (path.EndsWith(".exr"))
            {
                FIBITMAP exr = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_EXR, path, FREE_IMAGE_LOAD_FLAGS.RAW_DISPLAY);
                bmp = FreeImage.GetBitmap(FreeImage.ToneMapping(exr, FREE_IMAGE_TMO.FITMO_DRAGO03, 2.2, 0));
                FreeImage.Unload(exr);
            }
            //file *.svg
            else if (path.EndsWith(".svg"))
            {
                SvgDocument svg = SvgDocument.Open(path);
                bmp = svg.Draw();
            }
            //TARGA file *.tga
            else if (path.EndsWith(".tga"))
            {
                using (Paloma.TargaImage tar = new Paloma.TargaImage(path))
                {
                    bmp = new Bitmap(tar.Image);
                }
            }
            //WEBP file *.webp
            else if (path.EndsWith(".webp"))
            {
                bmp = ReadWebpFile(path);
            }
            //PHOTOSHOP file *.PSD
            else if (path.EndsWith(".psd"))
            {
                System.Drawing.PSD.PsdFile psd = (new System.Drawing.PSD.PsdFile()).Load(path);
                bmp = System.Drawing.PSD.ImageDecoder.DecodeImage(psd);
            }
            else
            {
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    bmp = new Bitmap(fs, true);

                    //GIF file *.gif
                    if (bmp.RawFormat.Equals(ImageFormat.Gif))
                    {
                        bmp = new Bitmap(path);
                    }
                    //ICON file *.ico
                    else if (bmp.RawFormat.Equals(ImageFormat.Icon))
                    {
                        bmp = ReadIconFile(path);
                    }
                    else if (bmp.RawFormat.Equals(ImageFormat.Jpeg))
                    {
                        //read Exif rotation
                        int rotation = GetRotation(bmp);
                        if (rotation != 0)
                        {
                            bmp = ScaleDownRotateBitmap(bmp, 1.0f, rotation);
                        }
                    }
                }
            }


            return(bmp);
        }
Пример #28
0
        public static Bitmap Load(string path)
        {
            path = path.ToLower();
            Bitmap bmp = null;

            //file *.hdr
            if (path.EndsWith(".hdr"))
            {
                FIBITMAP hdr = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_HDR, path, FREE_IMAGE_LOAD_FLAGS.RAW_DISPLAY);
                bmp = FreeImage.GetBitmap(FreeImage.ToneMapping(hdr, FREE_IMAGE_TMO.FITMO_DRAGO03, 2.2, 0));
                FreeImage.Unload(hdr);
            }
            //file *.exr
            else if (path.EndsWith(".exr"))
            {
                FIBITMAP exr = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_EXR, path, FREE_IMAGE_LOAD_FLAGS.RAW_DISPLAY);
                bmp = FreeImage.GetBitmap(FreeImage.ToneMapping(exr, FREE_IMAGE_TMO.FITMO_DRAGO03, 2.2, 0));
                FreeImage.Unload(exr);
            }
            //file *.svg
            else if (path.EndsWith(".svg"))
            {
                SvgDocument svg = SvgDocument.Open(path);
                bmp = svg.Draw();
            }
            //TARGA file *.tga
            else if (path.EndsWith(".tga"))
            {
                using (Paloma.TargaImage tar = new Paloma.TargaImage(path))
                {
                    bmp = new Bitmap(tar.Image);
                }
            }
            //WEBP file *.webp
            else if (path.EndsWith(".webp"))
            {
                bmp = ReadWebpFile(path);
            }
            //PHOTOSHOP file *.PSD
            else if (path.EndsWith(".psd"))
            {
                System.Drawing.PSD.PsdFile psd = (new System.Drawing.PSD.PsdFile()).Load(path);
                bmp = System.Drawing.PSD.ImageDecoder.DecodeImage(psd);
            }
            else
            {
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    bmp = new Bitmap(fs, true);

                    //GIF file *.gif
                    if (bmp.RawFormat.Equals(ImageFormat.Gif))
                    {
                        bmp = new Bitmap(path);
                    }
                    //ICON file *.ico
                    else if (bmp.RawFormat.Equals(ImageFormat.Icon))
                    {
                        bmp = ReadIconFile(path);
                    }
                    else if (bmp.RawFormat.Equals(ImageFormat.Jpeg))
                    {
                        //read Exif rotation
                        int rotation = GetRotation(bmp);
                        if (rotation != 0)
                        {
                            bmp = ScaleDownRotateBitmap(bmp, 1.0f, rotation);
                        }
                    }
                }
            }

            return bmp;
        }
Пример #29
0
        /// <summary>
        /// Returns a Stream instance with data from the specified item.
        /// </summary>
        /// <param name="ID">ID of the item to grab.</param>
        /// <returns>A Stream instance with data from the specified item.</returns>
        private static Stream GrabItem(ulong ID, FAR3TypeIDs TypeID)
        {
            MemoryStream MemStream = new MemoryStream();
            Bitmap BMap;

            m_StillLoading.WaitOne();

            foreach (FAR3Archive Archive in m_FAR3Archives)
            {
                if (Archive.ContainsEntry(ID))
                {
                    Stream Data = Archive.GrabEntry(ID);

                    if (!m_Assets.ContainsKey(ID))
                    {
                        switch(TypeID)
                        {
                            case FAR3TypeIDs.ANIM:
                                AddItem(ID, new Asset(ID, (uint)Data.Length, new Anim(Data)));
                                break;
                            case FAR3TypeIDs.APR:
                                AddItem(ID, new Asset(ID, (uint)Data.Length, new Appearance(Data)));
                                break;
                            case FAR3TypeIDs.BND:
                                AddItem(ID, new Asset(ID, (uint)Data.Length, new Binding(Data)));
                                break;
                            case FAR3TypeIDs.COL:
                                AddItem(ID, new Asset(ID, (uint)Data.Length, new Collection(Data)));
                                break;
                            case FAR3TypeIDs.HAG:
                                AddItem(ID, new Asset(ID, (uint)Data.Length, new HandGroup(Data)));
                                break;
                            case FAR3TypeIDs.MESH:
                                AddItem(ID, new Asset(ID, (uint)Data.Length, new Mesh(Data)));
                                break;
                            case FAR3TypeIDs.OFT:
                                AddItem(ID, new Asset(ID, (uint)Data.Length, new Outfit(Data)));
                                break;
                            case FAR3TypeIDs.PO:
                                AddItem(ID, new Asset(ID, (uint)Data.Length, new PurchasableOutfit(Data)));
                                break;
                            case FAR3TypeIDs.SKEL:
                                AddItem(ID, new Asset(ID, (uint)Data.Length, new Skeleton(Data)));
                                break;
                            case FAR3TypeIDs.TGA:
                                lock (MemStream)
                                {
                                    Paloma.TargaImage TGA = new Paloma.TargaImage(Data);
                                    TGA.Image.Save(MemStream, System.Drawing.Imaging.ImageFormat.Png);
                                    TGA.Dispose();
                                    MemStream.Seek(0, SeekOrigin.Begin);
                                    AddItem(ID, new Asset(ID, (uint)MemStream.Length,
                                        Texture2D.FromStream(m_Game.GraphicsDevice, MemStream)));
                                }
                                break;
                            case FAR3TypeIDs.PNG:
                            case FAR3TypeIDs.PackedPNG:
                                AddItem(ID, new Asset(ID, (uint)Data.Length,
                                    Texture2D.FromStream(m_Game.GraphicsDevice, Data)));
                                break;
                            case FAR3TypeIDs.JPG:
                                try
                                {
                                    BMap = new Bitmap(Data);
                                    BMap.MakeTransparent(System.Drawing.Color.FromArgb(255, 0, 255));
                                    BMap.MakeTransparent(System.Drawing.Color.FromArgb(255, 1, 255));
                                    BMap.MakeTransparent(System.Drawing.Color.FromArgb(254, 2, 254));
                                    BMap.Save(MemStream, System.Drawing.Imaging.ImageFormat.Png);
                                    BMap.Dispose();
                                    MemStream.Seek(0, SeekOrigin.Begin);

                                    AddItem(ID, new Asset(ID, (uint)MemStream.Length,
                                        Texture2D.FromStream(m_Game.GraphicsDevice, MemStream)));
                                }
                                catch
                                {
                                    try
                                    {
                                        MemStream.Dispose();
                                        AddItem(ID, new Asset(ID, (uint)Data.Length,
                                            Texture2D.FromStream(m_Game.GraphicsDevice, Data)));
                                    }
                                    catch(Exception) //Most likely a TGA, sigh.
                                    {
                                        MemStream = new MemoryStream();

                                        Paloma.TargaImage TGA = new Paloma.TargaImage(Data);
                                        TGA.Image.Save(MemStream, System.Drawing.Imaging.ImageFormat.Png);
                                        TGA.Dispose();
                                        MemStream.Seek(0, SeekOrigin.Begin);
                                        AddItem(ID, new Asset(ID, (uint)MemStream.Length,
                                            Texture2D.FromStream(m_Game.GraphicsDevice, MemStream)));
                                    }
                                }
                                break;
                            case FAR3TypeIDs.BMP:
                                if (IsBMP(Data))
                                {
                                    lock (MemStream)
                                    {
                                        try
                                        {
                                            BMap = new Bitmap(Data);
                                            BMap.MakeTransparent(System.Drawing.Color.FromArgb(255, 0, 255));
                                            BMap.MakeTransparent(System.Drawing.Color.FromArgb(255, 1, 255));
                                            BMap.MakeTransparent(System.Drawing.Color.FromArgb(254, 2, 254));
                                            BMap.Save(MemStream, System.Drawing.Imaging.ImageFormat.Png);
                                            BMap.Dispose();
                                            MemStream.Seek(0, SeekOrigin.Begin);

                                            AddItem(ID, new Asset(ID, (uint)MemStream.Length,
                                                Texture2D.FromStream(m_Game.GraphicsDevice, MemStream)));
                                        }
                                        catch (Exception)
                                        {
                                            MemStream.Dispose();

                                            AddItem(ID, new Asset(ID, (uint)Data.Length,
                                                Texture2D.FromStream(m_Game.GraphicsDevice, Data)));
                                        }
                                    }
                                }
                                else
                                {
                                    AddItem(ID, new Asset(ID, (uint)Data.Length,
                                        Texture2D.FromStream(m_Game.GraphicsDevice, Data)));
                                }
                                break;
                        }
                    }

                    return Data;
                }
            }

            return null;
        }