public Read ( byte array, int offset, int count ) : int | ||
array | byte | |
offset | int | |
count | int | |
return | int |
private void button3_Click(object sender, EventArgs e) { try { string str1 = textBox1.Text; string str2 = textBox2.Text + "\\" + textBox1.Text.Substring(textBox1.Text.LastIndexOf("\\") + 1, textBox1.Text.Length - textBox1.Text.LastIndexOf("\\") - 1); Stream myStream1, myStream2; BufferedStream myBStream1, myBStream2; byte[] myByte = new byte[1024]; int i; myStream1 = File.OpenRead(str1); myStream2 = File.OpenWrite(str2); myBStream1 = new BufferedStream(myStream1); myBStream2 = new BufferedStream(myStream2); i = myBStream1.Read(myByte, 0, 1024); while (i > 0) { myBStream2.Write(myByte, 0, i); i = myBStream1.Read(myByte, 0, 1024); } myBStream2.Flush(); myStream1.Close(); myBStream2.Close(); MessageBox.Show("文件复制完成"); } catch(Exception ex) { MessageBox.Show(ex.Message); } }
public static void Read_Arguments() { using (BufferedStream stream = new BufferedStream(new MemoryStream())) { byte[] array = new byte[10]; Assert.Throws<ArgumentNullException>("array", () => stream.Read(null, 1, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(array, -1, 1)); Assert.Throws<ArgumentOutOfRangeException>(() => stream.Read(array, 1, -1)); Assert.Throws<ArgumentException>(() => stream.Read(array, 9, 2)); } }
public static TransportMessage ToTransportMessage(this SqsTransportMessage sqsTransportMessage, IAmazonS3 amazonS3, SqsConnectionConfiguration connectionConfiguration) { var messageId = sqsTransportMessage.Headers[Headers.MessageId]; var result = new TransportMessage(messageId, sqsTransportMessage.Headers); if (!string.IsNullOrEmpty(sqsTransportMessage.S3BodyKey)) { var s3GetResponse = amazonS3.GetObject(connectionConfiguration.S3BucketForLargeMessages, sqsTransportMessage.S3BodyKey); result.Body = new byte[s3GetResponse.ResponseStream.Length]; using (BufferedStream bufferedStream = new BufferedStream(s3GetResponse.ResponseStream)) { int count; int transferred = 0; while ((count = bufferedStream.Read(result.Body, transferred, 8192)) > 0) { transferred += count; } } } else { result.Body = Convert.FromBase64String(sqsTransportMessage.Body); } result.TimeToBeReceived = sqsTransportMessage.TimeToBeReceived; if (sqsTransportMessage.ReplyToAddress != null) { result.Headers[Headers.ReplyToAddress] = sqsTransportMessage.ReplyToAddress.ToString(); } return result; }
public override void ShowUsage() { //BufferedStream类主要也是用来处理流数据的,但是该类主要的功能是用来封装其他流类。 //为什么要封装其他流类,这么做的意义是什么?按照微软的话说主要是减少某些流直接操作存储设备的时间。 //对于一些流来说直接向磁盘中存储数据这种做法的效率并不高,用BufferedStream包装过的流,先在内存中进行统一的处理再向磁盘中写入数据,也会提高写入的效率。 Console.WriteLine("BufferedStream类主要也是用来处理流数据的,但是该类主要的功能是用来封装其他流类。"); FileStream fileStream1 = File.Open(@"C:\NewText.txt", FileMode.OpenOrCreate, FileAccess.Read); //读取文件流 FileStream fileStream2 = File.Open(@"C:\Text2.txt", FileMode.OpenOrCreate, FileAccess.Write); //写入文件流 byte[] array4 = new byte[4096]; BufferedStream bufferedInput = new BufferedStream(fileStream1); //封装文件流 BufferedStream bufferedOutput = new BufferedStream(fileStream2); //封装文件流 int byteRead = bufferedInput.Read(array4, 0, array4.Length); bufferedOutput.Write(array4, 0, array4.Length); //= bufferedInput.Read(array4, 0, 4096); while (byteRead > 0) //读取到了数据 { bufferedOutput.Write(array4, 0, byteRead); Console.WriteLine(byteRead); break; }; bufferedInput.Close(); bufferedOutput.Close(); fileStream1.Close(); fileStream2.Close(); Console.ReadKey(); }
// ----------------- Dumping a .resources file ------------------ public DumpResource(String filename) { BufferedStream stream = new BufferedStream(Console.OpenStandardOutput()); Out = new StreamWriter(stream, new UTF8Encoding()); ResourceReader rr; if (filename.Equals("-")) { BufferedStream input = new BufferedStream(Console.OpenStandardInput()); // A temporary output stream is needed because ResourceReader expects // to be able to seek in the Stream. byte[] contents; { MemoryStream tmpstream = new MemoryStream(); byte[] buf = new byte[1024]; for (;;) { int n = input.Read(buf, 0, 1024); if (n == 0) break; tmpstream.Write(buf, 0, n); } contents = tmpstream.ToArray(); tmpstream.Close(); } MemoryStream tmpinput = new MemoryStream(contents); rr = new ResourceReader(tmpinput); } else { rr = new ResourceReader(filename); } foreach (DictionaryEntry entry in rr) // uses rr.GetEnumerator() DumpMessage(entry.Key as String, null, entry.Value as String); rr.Close(); Out.Close(); stream.Close(); }
public static byte[] GetFileContent(String smbUrl) { #if DEBUG_SAMBA Android.Util.Log.Debug("SmbClient", "Getting file content of " + smbUrl); #endif byte[] buffer = null; try { var file = new Jcifs.Smb.SmbFile(smbUrl); using (var sis = new System.IO.BufferedStream(new SambaInputStream(file))) { var length = file.Length(); buffer = new byte[length]; sis.Read(buffer, 0, (int)length); // will internally make several tries } } catch (Jcifs.Smb.SmbException ex) { LogException(ex); throw new System.IO.IOException(ex.Message, ex); } catch (Java.IO.IOException ex) { LogException(ex); throw new System.IO.IOException(ex.Message, ex); } catch (System.IO.IOException ex) { LogException(ex); throw; } return(buffer); }
public static Byte[] ToByte(this Stream InputStream) { BufferedStream bf = new BufferedStream(InputStream); byte[] buffer = new byte[InputStream.Length]; bf.Read(buffer, 0, buffer.Length); return buffer; }
//client side on wp didn't has BufferedStream because this, I'm need made //the implementation style it... protected MemoryStream ReadStream(BufferedStream stream, int bufferSize) { byte[] streamSize = new byte[4]; stream.Read(streamSize, 0, streamSize.Length); int totalStreamSize = BitConverter.ToInt32(streamSize, 0); return ReadStream(stream, bufferSize, totalStreamSize); }
public static byte[] convertFileToBufferData(string path) { FileStream fs = new FileStream(path,FileMode.Open); BufferedStream bf = new BufferedStream(fs); byte[] buffer = new byte[bf.Length]; bf.Read(buffer, 0, buffer.Length); byte[] buffer_new = buffer; return buffer_new; }
public void Read(byte[] data) { if (data == null || data.Length == 0) return; using (var buffer = new BufferedStream(new MemoryStream(data))) { var head = new byte[4]; buffer.Read(head, 0, head.Length); ReadHead(head); if (this.Length > 0) { var body = new byte[this.Length]; buffer.Read(body, 0, body.Length); ReadBody(body); ParseBody(); } } }
static TwoPlusTwo() { using (BufferedStream reader = new BufferedStream(new FileStream(HAND_RANK_DATA_FILENAME, FileMode.Open))) { reader.Read(b, 0, tableSize); } //for (int i = 0; i < HAND_RANK_SIZE; i++) //{ // HR[i] = BitConverter.ToInt32(b, i*4); //} }
/// <exception cref="IOException">The underlying stream is null or closed. </exception> /// <exception cref="DirectoryNotFoundException">The specified path is invalid, (for example, it is on an unmapped drive). </exception> /// <exception cref="UnauthorizedAccessException"><paramref name="path" /> specified a directory.-or- The caller does not have the required permission. </exception> /// <exception cref="FileNotFoundException">The file specified in <paramref name="path" /> was not found. </exception> /// <exception cref="CryptographicUnexpectedOperationException"><see cref="F:System.Security.Cryptography.HashAlgorithm.HashValue" /> is null. </exception> /// <exception cref="ObjectDisposedException">The object has already been disposed.</exception> /// <exception cref="ArgumentNullException"><paramref name="oldValue" /> is null. </exception> /// <exception cref="ArgumentException"><paramref name="oldValue" /> is the empty string (""). </exception> /// <exception cref="Exception">A delegate callback throws an exception.</exception> /// <exception cref="OperationCanceledException">The token has had cancellation requested.</exception> public string CalculateHash(string file, HashAlgorithm algorithm, CancellationToken token) { byte[] buffer; byte[] oldBuffer; int bytesRead; int oldBytesRead; long size; long totalBytesRead = 0; using (var bufferedStream = new BufferedStream(File.OpenRead(file))) { using (algorithm) { size = bufferedStream.Length; buffer = new byte[4096]; bytesRead = bufferedStream.Read(buffer, 0, buffer.Length); totalBytesRead += bytesRead; do { token.ThrowIfCancellationRequested(); oldBytesRead = bytesRead; oldBuffer = buffer; buffer = new byte[4096]; bytesRead = bufferedStream.Read(buffer, 0, buffer.Length); totalBytesRead += bytesRead; if (bytesRead == 0) { algorithm.TransformFinalBlock(oldBuffer, 0, oldBytesRead); } else { algorithm.TransformBlock(oldBuffer, 0, oldBytesRead, oldBuffer, 0); } HashProgressUpdate?.Invoke(this, new ProgressEventArgs((double) totalBytesRead*100/size)); } while (bytesRead != 0); return BitConverter.ToString(algorithm.Hash).Replace("-", string.Empty).ToUpper(); } } }
public void Stream2Test() { var ms = new BufferedStream(new MemoryStream()); Console.WriteLine(ms.CanWrite); Console.WriteLine(ms.CanRead); ms.Write(new byte[3] { 1, 2, 3 }, 0, 3); ms.Flush(); var bys = new byte[10]; var len = ms.Read(bys, 0, 10); Console.WriteLine(len + "->" + bys[0]); }
public static void CreateFileFromStream(Stream stream, string destination) { using (BufferedStream bufferedStream = new BufferedStream(stream)) { using (FileStream fileStream = File.OpenWrite(destination)) { byte[] buffer = new byte[8192]; int count; while ((count = bufferedStream.Read(buffer, 0, buffer.Length)) > 0) fileStream.Write(buffer, 0, count); } } }
//------------------------------------------------------------------------- private static void copyStreamToFile(System.IO.Stream stream, string destination) { using (System.IO.BufferedStream bs = new System.IO.BufferedStream(stream)) { using (System.IO.FileStream os = System.IO.File.OpenWrite(destination)) { byte[] buffer = new byte[2 * 4096]; int nBytes; while ((nBytes = bs.Read(buffer, 0, buffer.Length)) > 0) { os.Write(buffer, 0, nBytes); } } } }
protected ushort TextureWidth; // Vr Texture Width #endregion Fields #region Constructors /// <summary> /// Open a Vr texture from a file. /// </summary> /// <param name="file">Filename of the file that contains the texture data.</param> public VrTexture(string file) { byte[] data; try { using (BufferedStream stream = new BufferedStream(new FileStream(file, FileMode.Open, FileAccess.Read), 0x1000)) { data = new byte[stream.Length]; stream.Read(data, 0, data.Length); } } catch { data = new byte[0]; } TextureData = data; }
/// <summary> /// Gets the content body of the response. /// </summary> /// <remarks> /// The content body is assumed to be UTF8, consistent with the handling of <c>PutObjectRequest.ContentBody</c>. /// </remarks> /// <param name="response">The response to process.</param> /// <param name="encoding">The encoding of the body, or UTF8 if null.</param> /// <returns>The textual content of the response body.</returns> public static string GetResponseContentBody(this GetObjectResponse response, Encoding encoding = null) { if (encoding == null) encoding = Encoding.UTF8; var s = new MemoryStream(); BufferedStream bufferedStream = new BufferedStream(response.ResponseStream); byte[] buffer = new byte[ushort.MaxValue]; int bytesRead = 0; while ((bytesRead = bufferedStream.Read(buffer, 0, buffer.Length)) > 0) { s.Write(buffer, 0, bytesRead); } return encoding.GetString(s.ToArray()); }
public void CompareFile(FileStateInfo sample) { using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read)) using (BufferedStream bs = new BufferedStream(fs, chunksize)) { len = fs.Length; SampleFileStateInfo = sample; if (len < chunksize) { chunkcount = 1; } else { double chkcnt = len / chunksize; chkcnt = Math.Ceiling(chkcnt); chunkcount = (int)chkcnt + 1; } byte[] buffer = new byte[chunksize]; int bytesRead; int num = 0; reading = true; Thread t = new Thread(GetHashesAsync); t.Start(); while ((bytesRead = bs.Read(buffer, 0, chunksize)) != 0) //reading only 50mb chunks at a time { var stream = new BinaryReader(new MemoryStream(buffer)); Chunk chk = new Chunk(); chk.startposition = num * chunksize; chk.len = bytesRead; chk.data = new byte[bytesRead]; Buffer.BlockCopy(buffer, 0, chk.data, 0, bytesRead); chk.num = num; if (chk.data == null) { //MessageBox.Show("ERROR DATA IS NULL"); } tmpchunks.Push(chk); num++; RepProgress(num, chunkcount); GC.Collect(); } reading = false; do { Thread.Sleep(100); } while (tmpchunks.Count > 0 | GettingHashes); } }
public static byte[] ReadAllBytes(this Stream stream) { const int BUFF_SIZE = 4096; var buffer = new byte[BUFF_SIZE]; int bytesRead; var inStream = new BufferedStream(stream); var outStream = new MemoryStream(); while ((bytesRead = inStream.Read(buffer, 0, BUFF_SIZE)) > 0) { outStream.Write(buffer, 0, bytesRead); } return outStream.ToArray(); }
// internal McdFile(string basename, string directory) // { // BufferedStream file = new BufferedStream(File.OpenRead(directory+basename+".MCD")); // int diff = 0; // if(basename == "XBASES05") // diff=3; // tiles = new Tile[(file.Length/62)-diff]; // PckFile f = GameInfo.GetPckFile(basename,directory,2); // for(int i=0;i<tiles.Length;i++) // { // byte[] info = new byte[62]; // file.Read(info,0,62); // tiles[i] = new Tile(i,f,new McdEntry(info),this); // } // // foreach(Tile t in tiles) // t.Tiles = tiles; // file.Close(); // } internal McdFile(string basename, string directory, PckFile f) { BufferedStream file = new BufferedStream(File.OpenRead(directory+basename+".MCD")); int diff = 0; if(basename == "XBASES05") diff=3; tiles = new XCTile[(((int)file.Length)/62)-diff]; for(int i=0;i<tiles.Length;i++) { byte[] info = new byte[62]; file.Read(info,0,62); tiles[i] = new XCTile(i,f,new McdEntry(info),this); } foreach(XCTile t in tiles) t.Tiles = tiles; file.Close(); }
/// <summary> /// Reads all bytes of the supplied stream. /// </summary> public static byte[] ReadAllBytes(this Stream stream) { int buffSize = 1024; byte[] buffer = new byte[buffSize]; int bytesRead = 0; using (BufferedStream inStream = new BufferedStream(stream)) { using (MemoryStream outStream = new MemoryStream()) { while ((bytesRead = inStream.Read(buffer, 0, buffSize)) > 0) { outStream.Write(buffer, 0, bytesRead); } return outStream.ToArray(); } } }
static void Main(string[] args) { FileStream fs = new FileStream("Hoo.txt", FileMode.Create, FileAccess.ReadWrite); BufferedStream bs = new BufferedStream(fs); Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position); for (int i = 0; i < 64; i++) { bs.WriteByte((byte)i); } Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position); Console.WriteLine("\nContents:"); byte[] ba = new byte[bs.Length]; bs.Position = 0; bs.Read(ba, 0, (int)bs.Length); foreach (byte b in ba) { Console.Write("{0, -3}", b); } string s = "Foo"; for (int i = 0; i < 3; i++) { bs.WriteByte((byte)s[i]); } Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position); for (int i = 0; i < (256-67) + 1; i++) { bs.WriteByte((byte)i); } Console.WriteLine("Length: {0}\tPosition: {1}", bs.Length, bs.Position); bs.Close(); Console.ReadLine(); }
public void FetchFileFromServer() { TcpClient client = new TcpClient(hostName, port); if (client.Connected) { NetworkStream netStream = client.GetStream(); try { BufferedStream s_in = new BufferedStream(netStream); byte[] buffer = new byte[8192]; int bytesRead; string filePath = folderPath + requestedFile + ".mp3"; Stream s_out = File.OpenWrite(filePath); while ((bytesRead = s_in.Read(buffer, 0, 8192)) > 0) { s_out.Write(buffer, 0, bytesRead); } s_out.Flush(); s_in.Close(); s_out.Close(); if (File.Exists(filePath)) { Song song = new Song(filePath); string artist = song.Artist; string title = song.Title; requestedFilePath=folderPath+artist+"-"+title+".mp3"; File.Move(filePath,requestedFilePath); } } catch (Exception ex) { } } }
public static long FindPosition(Stream stream, byte[] byteSequence) { if (byteSequence.Length > stream.Length) return -1; byte[] buffer = new byte[byteSequence.Length]; using (BufferedStream bufStream = new BufferedStream(stream, byteSequence.Length)) { int i; while ((i = bufStream.Read(buffer, 0, byteSequence.Length)) == byteSequence.Length) { if (byteSequence.SequenceEqual(buffer)) return bufStream.Position - byteSequence.Length; else bufStream.Position -= byteSequence.Length - PadLeftSequence(buffer, byteSequence); } } return -1; }
/** * Reading bytes from stream * * @param count bytes count * @param stream source stream * @return readed bytes * @throws IOException reading exception */ public static byte[] readBytes(int count, /*InputStream*/ BufferedStream stream) { try { byte[] res = new byte[count]; int offset = 0; while (offset < res.Length) { int readed = stream.Read(res, offset, res.Length - offset); if (readed > 0) { offset += readed; } else if (readed < 0) { throw new IOException(); } else { Thread.Yield(); } } return res; } catch(IOException e) { System.Diagnostics.Debug.WriteLine(e.StackTrace); throw e; } }
private void btnSelect_Click(object sender, EventArgs e) { // Displays an OpenFileDialog so the user can select a Cursor. OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.Filter = "jpg|*.jpg"; openFileDialog1.Title = "Selecione uma imagem"; // Show the Dialog. // If the user clicked OK in the dialog and // a .CUR file was selected, open it. if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) { System.IO.BufferedStream bf = new BufferedStream(openFileDialog1.OpenFile()); byte[] buffer = new byte[bf.Length]; bf.Read(buffer,0,buffer.Length); MemoryStream ms = new MemoryStream(buffer); pbImagem.Image = Redimensiona(Image.FromStream(ms)); Imagem = imageToByteArray(pbImagem.Image); } }
static void Main(string[] args) { string input = "Some input"; byte[] bytes = Encoding.ASCII.GetBytes(input); MemoryStream memory = new MemoryStream(); BufferedStream buffered = new BufferedStream(memory); Console.WriteLine("Before Write:"); Console.WriteLine("Memory Position: {0}", memory.Position); Console.WriteLine("Buffered Position: {0}", buffered.Position); memory.Write(bytes, 0, bytes.Length); Console.WriteLine("\nAfter Write, Before Seek():"); Console.WriteLine("Memory Position: {0}", memory.Position); Console.WriteLine("Buffered Position: {0}", buffered.Position); memory.Seek(0, SeekOrigin.Begin); Console.WriteLine("\nAfter Seek():"); Console.WriteLine("Memory Position: {0}", memory.Position); Console.WriteLine("Buffered Position: {0}", buffered.Position); byte[] buffer = new byte[256]; int read = buffered.Read(buffer, 0, buffer.Length); Console.WriteLine("After Read():"); Console.WriteLine("Memory Position: {0}", memory.Position); Console.WriteLine("Buffered Position: {0}", buffered.Position); byte[] output = new byte[read]; Array.Copy(buffer, output, read); Console.WriteLine("Read {0} bytes", read); Console.WriteLine("Output: ***{0}***", Encoding.ASCII.GetString(output)); }
/// <summary> /// Open a Vr texture from a stream. /// </summary> /// <param name="stream">Stream that contains the texture data.</param> public VrTexture(Stream stream) { stream.Seek(0, SeekOrigin.Begin); // Seek to the beginning if (stream is MemoryStream) // We can use ToArray() for memory streams { try { TextureData = (stream as MemoryStream).ToArray(); } catch { TextureData = new byte[0]; } } else { byte[] data; try { using (BufferedStream bufStream = new BufferedStream(stream, 0x1000)) { data = new byte[bufStream.Length]; bufStream.Read(data, 0, data.Length); } } catch { data = new byte[0]; } TextureData = data; } }
void Process(string inPath, string outPath) { var buffer = new byte[BufferSize]; var generator = BuildGenerator(); using (var reader = new BufferedStream(new FileStream(inPath, FileMode.Open))) using (var writer = new BufferedStream(new FileStream(outPath, FileMode.Create))) { while (true) { var read = reader.Read(buffer, 0, BufferSize); if (read == 0) { break; } for (var i = 0; i < read; i++) { generator.MoveNext(); buffer[i] = (byte) (buffer[i] ^ generator.Current); } writer.Write(buffer, 0, read); } } }
public bool IsDirectPrintingSupported(Image image) { bool flag = false; if (image.RawFormat.Equals(ImageFormat.Jpeg) || image.RawFormat.Equals(ImageFormat.Png)) { MemoryStream stream = new MemoryStream(); try { image.Save(stream, image.RawFormat); stream.Position = 0L; using (BufferedStream stream2 = new BufferedStream(stream)) { int length = (int) stream2.Length; byte[] buffer = new byte[length]; stream2.Read(buffer, 0, length); int inData = image.RawFormat.Equals(ImageFormat.Jpeg) ? 0x1017 : 0x1018; int outData = 0; DeviceContext wrapper = this.CreateInformationContext(this.DefaultPageSettings); HandleRef hDC = new HandleRef(wrapper, wrapper.Hdc); try { if (SafeNativeMethods.ExtEscape(hDC, 8, Marshal.SizeOf(typeof(int)), ref inData, 0, out outData) > 0) { flag = (SafeNativeMethods.ExtEscape(hDC, inData, length, buffer, Marshal.SizeOf(typeof(int)), out outData) > 0) && (outData == 1); } } finally { wrapper.Dispose(); } return flag; } } finally { stream.Close(); } } return flag; }
static void DecodeVrTexture(string[] args) { // Get the command line arguments int OutFileArgIndex = Array.IndexOf(args, "-o"); int ClutArgIndex = Array.IndexOf(args, "-c"); int AutoClutArgIndex = Array.IndexOf(args, "-ac"); // Get the strings in the command line arguments string InputFile = args[1]; string OutputFile = (OutFileArgIndex != -1 && OutFileArgIndex < args.Length ? args[OutFileArgIndex + 1] : Path.GetFileNameWithoutExtension(InputFile) + ".png"); string ClutFile = (ClutArgIndex != -1 && AutoClutArgIndex == -1 && ClutArgIndex < args.Length ? args[ClutArgIndex + 1] : null); string InputPath = (Path.GetDirectoryName(InputFile) != String.Empty ? Path.GetDirectoryName(InputFile) + Path.DirectorySeparatorChar : String.Empty); string OutputPath = InputPath; // Load the data (as a byte array) if (!File.Exists(args[1])) { Console.WriteLine("ERROR: {0} does not exist.", Path.GetFileNameWithoutExtension(args[1])); return; } byte[] VrData = new byte[0]; using (BufferedStream stream = new BufferedStream(new FileStream(args[1], FileMode.Open, FileAccess.Read))) { VrData = new byte[stream.Length]; stream.Read(VrData, 0x00, VrData.Length); } Console.WriteLine("Vr Conv"); Console.WriteLine("------------------------"); Console.WriteLine("Decoding: {0}", Path.GetFileName(InputFile)); // Start the watch to see how long it takes to decode bool DecodeSuccess = false; MemoryStream BitmapData = null; Stopwatch timer = Stopwatch.StartNew(); // Decode the data now if (GvrTexture.IsGvrTexture(VrData)) { if (AutoClutArgIndex != -1) ClutFile = InputPath + Path.GetFileNameWithoutExtension(InputFile) + ".gvp"; DecodeSuccess = new VrDecoder.Gvr().DecodeTexture(VrData, ClutFile, out BitmapData); } else if (PvrTexture.IsPvrTexture(VrData)) { if (AutoClutArgIndex != -1) ClutFile = InputPath + Path.GetFileNameWithoutExtension(InputFile) + ".pvp"; DecodeSuccess = new VrDecoder.Pvr().DecodeTexture(VrData, ClutFile, out BitmapData); } else if (SvrTexture.IsSvrTexture(VrData)) { if (AutoClutArgIndex != -1) ClutFile = InputPath + Path.GetFileNameWithoutExtension(InputFile) + ".svp"; DecodeSuccess = new VrDecoder.Svr().DecodeTexture(VrData, ClutFile, out BitmapData); } else Console.WriteLine("ERROR: Not a Gvr, Pvr, or Svr texture."); // Was the data decoded successfully? if (DecodeSuccess && BitmapData != null) { try { using (BufferedStream stream = new BufferedStream(new FileStream(OutputPath + OutputFile, FileMode.Create, FileAccess.Write))) BitmapData.WriteTo(stream); } catch (Exception e) { Console.WriteLine("ERROR: Unable to output texture."); Console.WriteLine(e.ToString()); } timer.Stop(); Console.WriteLine("Texture decoded in {0} ms.", timer.ElapsedMilliseconds); } else if (DecodeSuccess && BitmapData == null) Console.WriteLine("ERROR: Unable to decode texture."); Console.WriteLine(); }
static void EncodeVrTexture(string[] args) { // Fixed! // Get the command line arguments int OutFileArgIndex = Array.IndexOf(args, "-o"); int ClutArgIndex = Array.IndexOf(args, "-c"); int GlobalIndexArgIndex = Array.IndexOf(args, "-gi"); // Get the strings in the command line arguments string InputFile = args[1]; string OutputFile = String.Empty; string ClutFile = String.Empty; string InputPath = (Path.GetDirectoryName(InputFile) != String.Empty ? Path.GetDirectoryName(InputFile) + Path.DirectorySeparatorChar : String.Empty); string OutputPath = InputPath; // Get the global index and convert it to a string uint GlobalIndex = 0; if (GlobalIndexArgIndex != -1 && args.Length > GlobalIndexArgIndex + 1) { if (!uint.TryParse(args[GlobalIndexArgIndex + 1], out GlobalIndex)) GlobalIndex = 0; } // Get the format string VrFormat = (args.Length > 2 ? args[2].ToLower() : null); string PixelFormat = (args.Length > 3 ? args[3].ToLower() : null); string DataFormat = (args.Length > 4 ? args[4].ToLower() : null); // Make sure the vr format is correct if (VrFormat != "gvr" && VrFormat != "pvr" && VrFormat != "svr") { Console.WriteLine("ERROR: Unknown vr format: {0}", (VrFormat == null ? "null" : VrFormat)); return; } // Load the data (as a byte array) if (!File.Exists(args[1])) { Console.WriteLine("ERROR: {0} does not exist.", Path.GetFileNameWithoutExtension(args[1])); return; } byte[] BitmapData = new byte[0]; using (BufferedStream stream = new BufferedStream(new FileStream(args[1], FileMode.Open, FileAccess.Read))) { BitmapData = new byte[stream.Length]; stream.Read(BitmapData, 0x00, BitmapData.Length); } Console.WriteLine("Vr Conv"); Console.WriteLine("------------------------"); Console.WriteLine("Encoding: {0}", Path.GetFileName(InputFile)); // Start the watch to see how long it takes to encode and set our variables bool EncodeSuccess = false; MemoryStream TextureData = null; MemoryStream ClutData = null; Stopwatch timer = Stopwatch.StartNew(); if (VrFormat == "gvr") { // Convert to a pvr OutputFile = (OutFileArgIndex != -1 && OutFileArgIndex < args.Length ? args[OutFileArgIndex + 1] : Path.GetFileNameWithoutExtension(InputFile) + ".gvr"); ClutFile = (ClutArgIndex != -1 && ClutArgIndex < args.Length ? args[ClutArgIndex + 1] : Path.GetFileNameWithoutExtension(OutputFile) + ".gvp"); EncodeSuccess = new VrEncoder.Gvr().EncodeTexture(BitmapData, PixelFormat, DataFormat, true, GlobalIndex, out TextureData, out ClutData); } if (VrFormat == "pvr") { // Pvr Unique Args int CompressionArgIndex = Array.IndexOf(args, "-cmp"); string CompressionFormat = (CompressionArgIndex != -1 && args.Length > CompressionArgIndex + 1 ? args[CompressionArgIndex + 1] : null); // Convert to a pvr OutputFile = (OutFileArgIndex != -1 && OutFileArgIndex < args.Length ? args[OutFileArgIndex + 1] : Path.GetFileNameWithoutExtension(InputFile) + ".pvr"); ClutFile = (ClutArgIndex != -1 && ClutArgIndex < args.Length ? args[ClutArgIndex + 1] : Path.GetFileNameWithoutExtension(OutputFile) + ".pvp"); EncodeSuccess = new VrEncoder.Pvr().EncodeTexture(BitmapData, PixelFormat, DataFormat, CompressionFormat, true, GlobalIndex, out TextureData, out ClutData); } else if (VrFormat == "svr") { // Convert to a svr OutputFile = (OutFileArgIndex != -1 && OutFileArgIndex < args.Length ? args[OutFileArgIndex + 1] : Path.GetFileNameWithoutExtension(InputFile) + ".svr"); ClutFile = (ClutArgIndex != -1 && ClutArgIndex < args.Length ? args[ClutArgIndex + 1] : Path.GetFileNameWithoutExtension(OutputFile) + ".svp"); EncodeSuccess = new VrEncoder.Svr().EncodeTexture(BitmapData, PixelFormat, DataFormat, true, GlobalIndex, out TextureData, out ClutData); } // Was the data encoded successfully? if (EncodeSuccess && TextureData != null) { try { using (BufferedStream stream = new BufferedStream(new FileStream(OutputPath + OutputFile, FileMode.Create, FileAccess.Write))) TextureData.WriteTo(stream); } catch (Exception e) { Console.WriteLine("ERROR: Unable to output texture."); Console.WriteLine(e.ToString()); } } else if (EncodeSuccess && TextureData == null) Console.WriteLine("ERROR: Unable to encode texture."); // Was the clut encoded successfully? if (EncodeSuccess && ClutData != null) { try { using (BufferedStream stream = new BufferedStream(new FileStream(OutputPath + ClutFile, FileMode.Create, FileAccess.Write))) ClutData.WriteTo(stream); } catch (Exception e) { Console.WriteLine("ERROR: Unable to output texture."); Console.WriteLine(e.ToString()); } } // Stop the timer if everything was encoded. if (EncodeSuccess && TextureData != null) { timer.Stop(); Console.WriteLine("Texture encoded in {0} ms.", timer.ElapsedMilliseconds); } }