public Stream GetRequestWrappingStream(Stream sourceStream) { Assert.IsNotNull(sourceStream, "getRequestWrappingStream test hook was called with null request stream"); WrappingStream wrappedStream = new WrappingStream(sourceStream); requestWrappingStreams.Add(wrappedStream); return wrappedStream; }
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext?context) { // don't let StreamWriter close the stream using var wrappingStream = new WrappingStream(stream, Ownership.None); using var writer = new StreamWriter(wrappingStream); await writer.WriteAsync(Json).ConfigureAwait(false); }
/// <summary> /// 指定したURLのサムネイルを取得します。 /// </summary> /// <param name="url">URL</param> /// <returns></returns> public static async Task <BitmapImage> ToThumbnail(string url) { return(await System.Windows.Application.Current.Dispatcher.Invoke(async() => { byte[] bytes = default(byte[]); try { using (var client = new HttpClient()) { bytes = await client.GetByteArrayAsync(url); } } catch { return null; } using (WrappingStream stream = new WrappingStream(new MemoryStream(bytes))) { BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = stream; bitmap.DecodePixelWidth = 160 + 48 * ((int)SettingModel.Instance.Thumbnail); bitmap.DecodePixelHeight = 120 + 36 * ((int)SettingModel.Instance.Thumbnail); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); if (bitmap.CanFreeze) { bitmap.Freeze(); } return bitmap; } })); }
public void SetUp() { m_memStream = new MemoryStream(); m_memStream.Write(s_streamData, 0, s_streamData.Length); m_stream = new WrappingStream(m_memStream, Ownership.None); }
/// <summary> /// 指定したURLのサムネイルを取得します。 /// </summary> /// <param name="url">URL</param> /// <returns></returns> public static async Task <BitmapImage> ToThumbnail(string url) { try { byte[] bytes = default(byte[]); using (var client = new HttpClient()) { bytes = await client.GetByteArrayAsync(url).ConfigureAwait(false); } using (WrappingStream stream = new WrappingStream(new MemoryStream(bytes))) { BitmapImage bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = stream; bitmap.DecodePixelWidth = 160 + 48 * 0; bitmap.DecodePixelHeight = 120 + 36 * 0; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); if (bitmap.CanFreeze) { bitmap.Freeze(); } return(bitmap); } } catch { return(null); } }
private static BitmapImage CreateImage(byte[] bytes) { BitmapImage image; try { // early I created BitmapFrame but it appers to consuming REALLY a lot of memory (about 1gig after loading 400 images) // So it sucks // bitmap = BitmapFrame.Create(wpapper, BitmapCreateOptions.None, BitmapCacheOption.OnLoad); using (var wpapper = new WrappingStream(new MemoryStream(bytes))) { image = new BitmapImage(); image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = wpapper; image.EndInit(); image.Freeze(); } } catch (Exception e) { //Todo add logging image = null; } return(image); }
/// <summary> /// Parses the JSON into an object of the specified type. /// </summary> /// <param name="response">The response.</param> /// <param name="type">The type.</param> /// <param name="jsonSettings">The JSON settings.</param> /// <returns>An object of the specified type.</returns> /// <exception cref="WebServiceException">The response content does not use the JSON content type, or the content is empty, /// or the text is not valid JSON, or the JSON cannot be deserialized into the specified type.</exception> /// <remarks>Use JToken as the type to parse arbitrary JSON.</remarks> public static async Task <object?> GetJsonAsAsync(this HttpResponseMessage response, Type type, JsonSettings?jsonSettings) { try { // StreamReader will throw an ArgumentException when Stream.CanRead is false. It's suspected that this // might happen if the HTTP request is canceled (via HttpClient.Timeout) before the response is read. var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); if (!responseStream.CanRead) { throw HttpResponseMessageUtility.CreateWebServiceException(response, "Response stream is not readable."); } // parse JSON to desired value using var wrappingStream = new WrappingStream(responseStream, Ownership.None); using var reader = new StreamReader(wrappingStream); return(JsonUtility.FromJsonTextReader(reader, type, jsonSettings)); } catch (JsonReaderException x) { // JSON invalid throw HttpResponseMessageUtility.CreateWebServiceException(response, "Response is not valid JSON: " + x.Message, x); } catch (JsonSerializationException x) { // JSON can't be deserialized throw HttpResponseMessageUtility.CreateWebServiceException(response, "Response JSON could not be deserialized to {0}: {1}".FormatInvariant(type, x.Message), x); } }
/// <summary> /// Reads a content preview from the response. /// </summary> /// <param name="response">The response.</param> /// <returns>The content preview.</returns> public static async Task <string> ReadContentPreviewAsync(HttpResponseMessage response) { try { Stream stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); using (WrappingStream wrappingStream = new WrappingStream(stream, Ownership.None)) using (StreamReader reader = new StreamReader(stream)) { char[] buffer = new char[c_contentPreviewCharacterCount]; int readCount = await reader.ReadBlockAsync(buffer, 0, buffer.Length).ConfigureAwait(false); if (readCount == buffer.Length) { buffer[readCount - 1] = '\u2026'; } return(new string(buffer, 0, readCount)); } } catch (Exception) { // ignore failure to read a content preview return(null); } }
private static BitmapImage CreateImage(byte[] b, int dpw, int dph) { try { using (var ms = new MemoryStream(b, false)) using (var ws = new WrappingStream(ms)) { var bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.StreamSource = ws; if (dpw > 0 || dph > 0) { bi.DecodePixelWidth = dpw; bi.DecodePixelHeight = dph; } bi.EndInit(); bi.Freeze(); return(bi); } } catch { return(null); } }
public void SetUp() { m_memStream = new MemoryStream(); m_memStream.Write(s_streamData, 0, s_streamData.Length); m_stream = new WrappingStream(m_memStream, Ownership.None); }
public Streams(IISHttpContext context) { _context = context; _request = new HttpRequestStream(_context); _response = new HttpResponseStream(_context, _context); _upgradeableResponse = new WrappingStream(_response); _upgradeableRequest = new WrappingStream(_request); }
private static BitmapSource Load() { using (var stream = new WrappingStream(new MemoryStream(BinaryResources.BrokenImage))) { var bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.StreamSource = stream; bi.EndInit(); bi.Freeze(); return bi; } }
/// <summary> /// Обновление LV /// </summary> /// <param name="img"></param> private void Handler_LiveViewUpdated(Stream img) { using (var wr = new WrappingStream(img)) { var bmp = new BitmapImage(); bmp.BeginInit(); bmp.StreamSource = wr; bmp.EndInit(); bmp.Freeze(); Application.Current.Dispatcher.Invoke(_setLiveView, bmp); } }
private static BitmapSource Load() { using (var stream = new WrappingStream(new MemoryStream(BinaryResources.BrokenImage))) { var bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.StreamSource = stream; bi.EndInit(); bi.Freeze(); return(bi); } }
/// <summary> /// 画像ファイルのファイルサイズを取得します。 /// </summary> public static long GetFileSize(this BitmapSource bitmapSource) { var encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmapSource)); using (var wrappingStream = new WrappingStream(new MemoryStream())) { encoder.Save(wrappingStream); return(wrappingStream.Length); } }
public BodyControl(IHttpBodyControlFeature bodyControl, IHttpResponseControl responseControl) { _requestReader = new HttpRequestPipeReader(); _request = new HttpRequestStream(bodyControl, _requestReader); _emptyRequestReader = new HttpRequestPipeReader(); _emptyRequest = new HttpRequestStream(bodyControl, _emptyRequestReader); _responseWriter = new HttpResponsePipeWriter(responseControl); _response = new HttpResponseStream(bodyControl, _responseWriter); _upgradeableResponse = new WrappingStream(_response); _upgradeStream = new HttpUpgradeStream(_request, _response); }
public byte[] ToPixels(string paPath) { byte[] pixels; using (var stream = File.OpenRead(paPath)) { using (var wrapper = new WrappingStream(stream)) { using (var bmp = (Bitmap)System.Drawing.Image.FromStream(wrapper)) { Bitmap resized = null; if (bmp.Width != _size.Width || bmp.Height != _size.Height) { resized = (Bitmap)FixedSize(bmp, _size.Width, _size.Height); } else { resized = bmp; } using (resized) { lock (Sync) { pixels = ReadBytePixels(resized); } } } } } Array.Copy(_bytePixelsClean, _bytePixels, _bytePixels.Length); var index = 0; if (!_grayScale) { for (int i = 0; i < pixels.Length; i++) { if (_channels[i % 4]) { _bytePixels[index++] = pixels[i]; } } } else { for (int i = 0; i < pixels.Length; i += 4) { _bytePixels[index++] = (byte)((pixels[i] + pixels[i + 1] + pixels[i + 2] + pixels[i + 3]) / 4.0); } } return(_bytePixels); }
public override string ToString() { var json = string.Empty; var serializer = new DataContractJsonSerializer(typeof(FontDialogResult)); using (var ms = new WrappingStream(new MemoryStream())) { serializer.WriteObject(ms, this); json = Encoding.UTF8.GetString(ms.ToArray()); } return(json); }
/// <summary> /// Byte配列の画像データからBitmapImageを生成します /// </summary> /// <param name="bytes">画像データ</param> /// <param name="freezing">生成したBitmapImageをFreezeする場合Trueを指定</param> /// <returns>BitmapImage</returns> public static BitmapImage CreateBitmap(byte[] bytes, bool freezing = true) { using (var stream = new WrappingStream(new MemoryStream(bytes))) { var bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = stream; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); bitmap.StreamSource = null; if (freezing && bitmap.CanFreeze) { bitmap.Freeze(); } return bitmap; } }
public static FontDialogResult FromString( string json) { var obj = default(FontDialogResult); var serializer = new DataContractJsonSerializer(typeof(FontDialogResult)); var data = Encoding.UTF8.GetBytes(json); using (var ms = new WrappingStream(new MemoryStream(data))) { obj = (FontDialogResult)serializer.ReadObject(ms); } return(obj); }
/// <summary> /// ビットマップ画像を生成します。 /// </summary> public static BitmapImage CreateBitmapImage(string filePath, bool freezing) { using (var wrappingStream = new WrappingStream(new MemoryStream(ConvertFileToBytes(filePath)))) { var bitmapImage = new BitmapImage(); bitmapImage.Initialize(wrappingStream); if (freezing) { bitmapImage.Freeze(); } return(bitmapImage); } }
public static BitmapImage CreateImageSource(Stream stream) { using (var wrapper = new WrappingStream(stream)) { using (var reader = new BinaryReader(wrapper)) { var imageSource = new BitmapImage(); imageSource.BeginInit(); imageSource.CacheOption = BitmapCacheOption.OnLoad; imageSource.StreamSource = reader.BaseStream; imageSource.EndInit(); imageSource.Freeze(); return imageSource; } } }
public static BitmapImage CreateImageSource(Stream stream) { using (var wrapper = new WrappingStream(stream)) { using (var reader = new BinaryReader(wrapper)) { var imageSource = new BitmapImage(); imageSource.BeginInit(); imageSource.CacheOption = BitmapCacheOption.OnLoad; imageSource.StreamSource = reader.BaseStream; imageSource.EndInit(); imageSource.Freeze(); return(imageSource); } } }
public void NamedStreams_PayloadDrivenMaterialization() { // Make sure DSSL properties can materialized and populated with the right url in non-projection cases { // Testing without projections (payload driven) and making sure one is able to project out the stream url DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4); context.EnableAtom = true; context.Format.UseAtom(); context.IgnoreMissingProperties = true; var q = context.CreateQuery <EntityWithStreamLink>("MySet1"); object entity = null; foreach (EntityWithStreamLink o in q) { Assert.IsNotNull(o.Stream1, "Stream1 must have some value"); Assert.AreEqual(o.Stream1.EditLink, context.GetReadStreamUri(o, "Stream1"), "the value in the entity descriptor must match with the property value"); Assert.IsNull(o.SomeRandomProperty, "SomeRandomProperty must be null, since the payload does not have the link with the property name"); entity = o; } // Try updating the entity and make sure that the link is not send back in the payload. context.UpdateObject(entity); WrappingStream wrappingStream = null; context.RegisterStreamCustomizer((inputStream) => { wrappingStream = new WrappingStream(inputStream); return(wrappingStream); }, null); try { context.SaveChanges(); Assert.Fail("Save changes should throw an exception"); } catch (Exception) { // do nothing } string payload = wrappingStream.GetLoggingStreamAsString(); Assert.IsTrue(payload.Contains("<d:ID m:type=\"Int32\">1</d:ID>"), "Id element must be present"); Assert.IsFalse(payload.Contains("Stream1Url"), "link url should not be sent in the payload"); } }
private void SDK_LiveViewUpdated(Stream img) { if (CameraHandler.IsLiveViewOn) { using (WrappingStream s = new WrappingStream(img)) { img.Position = 0; EvfImage = new BitmapImage(); EvfImage.BeginInit(); EvfImage.StreamSource = s; EvfImage.CacheOption = BitmapCacheOption.OnLoad; EvfImage.EndInit(); EvfImage.Freeze(); Application.Current.Dispatcher.Invoke(SetImageAction); } } }
private async Task EncodeByFFMEPG( string wave, Func <byte[], int, Task> sendDelegate) { var pi = new ProcessStartInfo { FileName = this.FFMpeg, Arguments = $"-i \"{wave}\" -ac 2 -f s16le -ar 48000 pipe:1", UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true, }; var ffmpeg = Process.Start(pi); var ffout = ffmpeg.StandardOutput.BaseStream; var bufferSize = 3840; // lets buffer ffmpeg output using (var ms = new WrappingStream(new MemoryStream())) { await ffout.CopyToAsync(ms); ms.Position = 0; var buff = new byte[bufferSize]; var br = 0; while ((br = ms.Read(buff, 0, buff.Length)) > 0) { // it's possible we got less than expected, let's null the remaining part of the buffer if (br < buff.Length) { for (var i = br; i < buff.Length; i++) { buff[i] = 0; } } // we're sending 20ms of data await sendDelegate(buff, 20); } } }
/// <summary> /// Implements the Dispose pattern /// </summary> /// <param name="disposing">Whether this object is being disposed via a call to Dispose /// or garbage collected.</param> protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (disposing) { if (this.CrcStream != null) { CrcStream.Dispose(); CrcStream = null; } if (this.WrappingStream != null) { WrappingStream.Dispose(); WrappingStream = null; } } this.disposed = true; } }
private void SetImage (BitmapImage image, Stream stream, GraphicInformation information, bool asThumbnail) { stream.Position = 0; if (asThumbnail && information.Type == GraphicFileType.Jpeg) { try { // Get JPEG thumbnail from header var frame = BitmapFrame.Create (stream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand); var source = frame.Thumbnail; if (source == null) { stream.Position = 0; this.SetStreamSourceToImage(image, stream); return; } using (var ms = new WrappingStream(new MemoryStream())) { var encoder = new JpegBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(source)); encoder.Save(ms); ms.Seek(0, SeekOrigin.Begin); this.SetStreamSourceToImage(image, ms); return; } } catch { } stream.Position = 0; } this.SetStreamSourceToImage(image, stream); }
private static BitmapImage LoadImage(string email) { if (NetworkInterface.GetIsNetworkAvailable() == false) return null; try { BitmapImage bitmap = null; var url = GenerateUrlFromEmail(email); using (var wc = new WebClient()) { var data = wc.DownloadData(url); Application.Current.Dispatcher.Invoke(() => { using (var stream = new WrappingStream(new MemoryStream(data))) { bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.StreamSource = stream; bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.EndInit(); bitmap.StreamSource = null; if (bitmap.CanFreeze) bitmap.Freeze(); } }); } Debug.Assert(bitmap != null); return bitmap; } catch { return null; } }
#pragma warning restore 1998 private void SetSourceToImage (BitmapImage image, Stream stream, GraphicInformation information, bool asThumbnail) { if (information.BlankHeaderLength == 0) { this.SetImage(image, stream, information, asThumbnail); } else { using (var ms = new WrappingStream(new MemoryStream((int) (stream.Length - information.BlankHeaderLength)))) { stream.Position = information.BlankHeaderLength; ms.Position = 0; stream.CopyTo(ms); this.SetImage(image, ms, information, asThumbnail); } } }
private void SDK_LiveViewUpdated(Stream img) { try { if (CameraHandler.IsLiveViewOn) { using (WrappingStream s = new WrappingStream(img)) { img.Position = 0; BitmapImage EvfImage = new BitmapImage(); EvfImage.BeginInit(); EvfImage.StreamSource = s; EvfImage.CacheOption = BitmapCacheOption.OnLoad; EvfImage.EndInit(); EvfImage.Freeze(); Application.Current.Dispatcher.Invoke(SetImageAction, EvfImage); } } } catch (Exception ex) { ReportError(ex.Message, false); } }
/// <summary> /// Parses the JSON into an object of the specified type. /// </summary> /// <param name="response">The response.</param> /// <param name="type">The type.</param> /// <param name="jsonSettings">The JSON settings.</param> /// <returns>An object of the specified type.</returns> /// <exception cref="WebServiceException">The response content does not use the JSON content type, or the content is empty, /// or the text is not valid JSON, or the JSON cannot be deserialized into the specified type.</exception> /// <remarks>Use JToken as the type to parse arbitrary JSON.</remarks> public static async Task <object> GetJsonAsAsync(this HttpResponseMessage response, Type type, JsonSettings jsonSettings) { try { // parse JSON to desired value Stream responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false); using (WrappingStream wrappingStream = new WrappingStream(responseStream, Ownership.None)) using (StreamReader reader = new StreamReader(wrappingStream)) return(JsonUtility.FromJsonTextReader(reader, type, jsonSettings)); } catch (JsonReaderException x) { // JSON invalid throw HttpResponseMessageUtility.CreateWebServiceException(response, "Response is not valid JSON: " + x.Message, x); } catch (JsonSerializationException x) { // JSON can't be deserialized throw HttpResponseMessageUtility.CreateWebServiceException(response, "Response JSON could not be deserialized to {0}: {1}".FormatInvariant(type, x.Message), x); } }
private static void DoDetectEncoding(Encoding encoding, string testPattern) { using (MemoryStream stream = new MemoryStream()) using (StreamWriter writer = new StreamWriter(stream, encoding)) { writer.Write(testPattern); writer.Flush(); // detect encoding stream.Position = 0; Encoding detected = StreamUtility.DetectBestEncoding(stream); Assert.IsNotNull(detected); Assert.AreEqual(encoding.CodePage, detected.CodePage); // use encoding to read stream using (WrappingStream wrappingStream = new WrappingStream(stream, Ownership.None)) using (StreamReader reader = new StreamReader(wrappingStream, detected, false)) { string read = reader.ReadToEnd(); Assert.AreEqual(testPattern, read); } } }
private static void DoDetectEncoding(Encoding encoding, string testPattern) { using (MemoryStream stream = new MemoryStream()) using (StreamWriter writer = new StreamWriter(stream, encoding)) { writer.Write(testPattern); writer.Flush(); // detect encoding stream.Position = 0; Encoding detected = StreamUtility.DetectBestEncoding(stream); Assert.IsNotNull(detected); Assert.AreEqual(encoding.CodePage, detected.CodePage); // use encoding to read stream using (WrappingStream wrappingStream = new WrappingStream(stream, Ownership.None)) using (StreamReader reader = new StreamReader(wrappingStream, detected, false)) { string read = reader.ReadToEnd(); Assert.AreEqual(testPattern, read); } } }
/// <summary> Display the loaded image. </summary> /// <param name="buffer"> The byte array containing the image data. </param> /// <param name="mapObjects"> Set of map objects. </param> /// <param name="mapParam"> The corresponding map parameters object. </param> private void DisplayImage(byte[] buffer, IEnumerable <IMapObject> mapObjects, MapParam mapParam) { // map viewport changed already if (mapParam.Index != index) { return; } lastZoom = MapView.FinalZoom; mapImage.Width = mapParam.Right - mapParam.Left; mapImage.Height = mapParam.Bottom - mapParam.Top; mapImage.Opacity = 1; SetLeft(mapImage, mapParam.Left + MapView.OriginOffset.X); SetTop(mapImage, -mapParam.Bottom + MapView.OriginOffset.Y); mapImage.Tag = mapParam; if (buffer == null) { mapImage.Source = null; return; } using (var stream = new MemoryStream(buffer)) using (var wrapper = new WrappingStream(stream)) { var bitmapImage = new BitmapImage(); bitmapImage.BeginInit(); bitmapImage.StreamSource = wrapper; bitmapImage.CacheOption = BitmapCacheOption.OnLoad; bitmapImage.EndInit(); bitmapImage.Freeze(); mapImage.Source = bitmapImage; } UpdateMapObjects?.Invoke(mapObjects, new Size(mapParam.Width, mapParam.Height)); }
public static BitmapImage Convert([CanBeNull] string id) { if (id == @"_") { id = null; // just in case } BitmapImage bi; if (Cache.TryGetValue(id ?? "", out bi)) { return(bi); } var bytes = GetFlagBytes(id); if (bytes == null) { Cache[id ?? ""] = null; return(null); } // WrappingSteam here helps to avoid memory leaks. For more information: // https://code.logos.com/blog/2008/04/memory_leak_with_bitmapimage_and_memorystream.html using (var memory = new MemoryStream(bytes)) using (var stream = new WrappingStream(memory)) { bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.StreamSource = stream; bi.EndInit(); bi.Freeze(); Cache[id ?? ""] = bi; return(bi); } }
/// <summary> /// Safe (handles all exceptions inside). /// </summary> private static BitmapEntry LoadBitmapSourceFromBytes(byte[] data, int decodeWidth = -1, int decodeHeight = -1, int attempt = 0) { try { // for more information about WrappingStream: https://code.logos.com/blog/2008/04/memory_leak_with_bitmapimage_and_memorystream.html using (var stream = new WrappingStream(new MemoryStream(data))) { int width = 0, height = 0; var bi = new BitmapImage(); bi.BeginInit(); if (decodeWidth > 0) { bi.DecodePixelWidth = (int)(decodeWidth * DpiAwareWindow.OptionScale); width = bi.DecodePixelWidth; } if (decodeHeight > 0) { bi.DecodePixelHeight = (int)(decodeHeight * DpiAwareWindow.OptionScale); height = bi.DecodePixelHeight; } bi.CacheOption = BitmapCacheOption.OnLoad; bi.StreamSource = stream; bi.EndInit(); bi.Freeze(); if (decodeWidth <= 0) { width = bi.PixelWidth; } if (decodeHeight <= 0) { height = bi.PixelHeight; } return new BitmapEntry(bi, width, height); } } catch (FileFormatException e) { // I AM THE GOD OF STUPID WORKAROUNDS, AND I BRING YOU, WORKAROUND! if (attempt++ < 2 && e.InnerException is COMException) { Logging.Warning("Recover attempt: " + attempt); return LoadBitmapSourceFromBytes(data, decodeWidth, decodeHeight, attempt); } Logging.Warning("Loading failed: " + e); return new BitmapEntry(); } catch (Exception e) { Logging.Warning("Loading failed: " + e); return new BitmapEntry(); } }
private void CreatePuzzle(Stream streamSource) { Random rnd = new Random(); var connections = new int[] { (int)ConnectionType.Tab, (int)ConnectionType.Blank }; png = null; imageSource = null; var uri = new Uri(destFileName); //We do this to avoid memory leaks using (WrappingStream wrapper = new WrappingStream(streamSource)) using (BinaryReader reader = new BinaryReader(wrapper)) { imageSource = new BitmapImage(); imageSource.BeginInit(); imageSource.CacheOption = BitmapCacheOption.OnLoad; imageSource.StreamSource = reader.BaseStream; // streamSource; imageSource.EndInit(); imageSource.Freeze(); } imgShowImage.Source = imageSource; scvImage.Visibility = Visibility.Hidden; cnvPuzzle.Visibility = Visibility.Visible; var angles = new int[] { 0, 90, 180, 270 }; int index = 0; for (var y = 0; y < rows; y++) { for (var x = 0; x < columns; x++) { if (x != 1000) { int upperConnection = (int)ConnectionType.None; int rightConnection = (int)ConnectionType.None; int bottomConnection = (int)ConnectionType.None; int leftConnection = (int)ConnectionType.None; if (y != 0) upperConnection = -1 * pieces[(y - 1) * columns + x].BottomConnection; if (x != columns - 1) rightConnection = connections[rnd.Next(2)]; if (y != rows - 1) bottomConnection = connections[rnd.Next(2)]; if (x != 0) leftConnection = -1 * pieces[y * columns + x - 1].RightConnection; int angle = 0; var piece = new Piece(imageSource, x, y, 0.1, 0.1, (int)upperConnection, (int)rightConnection, (int)bottomConnection, (int)leftConnection, false, index, scale); piece.SetValue(Canvas.ZIndexProperty, 1000 + x * rows + y); piece.MouseEnter += new MouseEventHandler(piece_MouseEnter); piece.MouseLeftButtonUp += new MouseButtonEventHandler(piece_MouseLeftButtonUp); piece.MouseRightButtonUp += new MouseButtonEventHandler(piece_MouseRightButtonUp); piece.Rotate(piece, angle); var shadowPiece = new Piece(imageSource, x, y, 0.1, 0.1, (int)upperConnection, (int)rightConnection, (int)bottomConnection, (int)leftConnection, true, shadowPieces.Count(), scale); shadowPiece.SetValue(Canvas.ZIndexProperty, x * rows + y); shadowPiece.Rotate(piece, angle); pieces.Add(piece); shadowPieces.Add(shadowPiece); index++; } } } var tt = new TranslateTransform() { X = 20, Y = 20 }; foreach (var p in pieces) { Random random = new Random(); int i = random.Next(0, pnlPickUp.Children.Count); p.ScaleTransform.ScaleX = 1.0; p.ScaleTransform.ScaleY = 1.0; p.RenderTransform = tt; p.X = -1; p.Y = -1; p.IsSelected = false; pnlPickUp.Children.Insert(i, p); double angle = angles[rnd.Next(0, 4)]; p.Rotate(p, angle); shadowPieces[p.Index].Rotate(p, angle); } rectSelection.SetValue(Canvas.ZIndexProperty, 5000); rectSelection.StrokeDashArray = new DoubleCollection(new double[] { 4, 4, 4, 4 }); cnvPuzzle.Children.Add(rectSelection); }
public static ImageSource ByteToImage(byte[] imageData) { BitmapImage biImg = new BitmapImage(); WrappingStream WS; using (MemoryStream ms = new MemoryStream(imageData)) { WS = new WrappingStream(ms); biImg.BeginInit(); biImg.CacheOption = BitmapCacheOption.OnLoad; biImg.StreamSource = WS; biImg.EndInit(); biImg.Freeze(); } WS.Dispose(); ImageSource imgSrc = biImg as ImageSource; return imgSrc; }
private void lookModsFile(string path) { if (Path.GetExtension(path) == ".ini") { if (File.Exists(path.Replace(".ini", ".fm"))) { BitmapImage bmIcon = null; BitmapImage bmImage = null; var parser = new FileIniDataParser(); IniData data; try { data = parser.ReadFile(path, Encoding.Unicode); } catch { data = parser.ReadFile(path); } string iconstring = data["FMMInfo"]["Icon"]; string imagefullstring = data["FMMInfo"]["ImageFull"]; string imagethumbstring = data["FMMInfo"]["ImageThumb"]; //icon loads Uri iconUri = null; if (!string.IsNullOrEmpty(iconstring) && !iconstring.Contains("/")) { if (File.Exists(Path.Combine(Directory.GetParent(path).FullName, iconstring))) { try { var mS = File.OpenRead(Path.Combine(Directory.GetParent(path).FullName, iconstring)); if (mS != null) { using (WrappingStream wrapper = new WrappingStream(mS)) { bmIcon = new BitmapImage(); bmIcon.BeginInit(); bmIcon.DecodePixelWidth = 200; bmIcon.CacheOption = BitmapCacheOption.OnLoad; bmIcon.StreamSource = wrapper; bmIcon.EndInit(); bmIcon.Freeze(); } mS.Dispose(); mS.Close(); } } catch { bmIcon = null; } } } else if (!offlineMode && !string.IsNullOrEmpty(iconstring) && Uri.TryCreate(iconstring, UriKind.Absolute, out iconUri)) { try { var mS = GetStreamFromUrl(iconstring); if (mS != null) { using (WrappingStream wrapper = new WrappingStream(mS)) { bmIcon = new BitmapImage(); bmIcon.BeginInit(); bmIcon.DecodePixelWidth = 200; bmIcon.CacheOption = BitmapCacheOption.OnLoad; bmIcon.StreamSource = wrapper; bmIcon.EndInit(); bmIcon.Freeze(); } mS.Dispose(); } } catch { bmIcon = null; } } //image loads Uri imageUri = null; if (!string.IsNullOrEmpty(imagefullstring) && !imagefullstring.Contains("/")) { if (File.Exists(Path.Combine(Directory.GetParent(path).FullName, imagefullstring))) { try { var mS = File.OpenRead(Path.Combine(Directory.GetParent(path).FullName, imagefullstring)); if (mS != null) { using (WrappingStream wrapper = new WrappingStream(mS)) { bmImage = new BitmapImage(); bmImage.BeginInit(); bmImage.DecodePixelWidth = 200; bmImage.CacheOption = BitmapCacheOption.OnLoad; bmImage.StreamSource = wrapper; bmImage.EndInit(); bmImage.Freeze(); } mS.Dispose(); mS.Close(); } } catch { bmImage = null; } } } else if (!string.IsNullOrEmpty(imagethumbstring) && !imagethumbstring.Contains("/")) { if (File.Exists(Path.Combine(Directory.GetParent(path).FullName, imagethumbstring))) { try { var mS = File.OpenRead(Path.Combine(Directory.GetParent(path).FullName, imagethumbstring)); if (mS != null) { using (WrappingStream wrapper = new WrappingStream(mS)) { bmImage = new BitmapImage(); bmImage.BeginInit(); bmImage.DecodePixelWidth = 200; bmImage.CacheOption = BitmapCacheOption.OnLoad; bmImage.StreamSource = wrapper; bmImage.EndInit(); bmImage.Freeze(); } mS.Dispose(); mS.Close(); } } catch { bmImage = null; } } } else if (!offlineMode && !string.IsNullOrEmpty(imagethumbstring) && Uri.TryCreate(imagethumbstring, UriKind.Absolute, out imageUri) && (imagethumbstring.EndsWith(".png") || imagethumbstring.EndsWith(".jpg") || imagethumbstring.EndsWith(".bmp"))) { try { var mS = GetStreamFromUrl(imagethumbstring); if (mS != null) { using (WrappingStream wrapper = new WrappingStream(mS)) { bmImage = new BitmapImage(); bmImage.BeginInit(); bmImage.DecodePixelWidth = 200; bmImage.CacheOption = BitmapCacheOption.OnLoad; bmImage.StreamSource = wrapper; bmImage.EndInit(); bmImage.Freeze(); } mS.Dispose(); } } catch { bmImage = null; } } Dispatcher.Invoke(new Action(() => { Mod newMod = new Mod(); newMod.Name = data["FMMInfo"]["Name"]; newMod.Author = data["FMMInfo"]["Author"]; newMod.Version = data["FMMInfo"]["Version"]; newMod.Desc = data["FMMInfo"]["Desc"]; newMod.LongDesc = data["FMMInfo"]["LongDesc"]; newMod.Warnings = data["FMMInfo"]["Warnings"]; newMod.LongWarnings = data["FMMInfo"]["LongWarnings"]; newMod.Url = data["FMMInfo"]["Url"]; newMod.ImageFull = data["FMMInfo"]["ImageFull"]; newMod.EDVersion = data["FMMInfo"]["EDVersion"]; newMod.RevisionDate = data["FMMInfo"]["RevisionDate"]; newMod.Credits = data["FMMInfo"]["Credits"]; newMod.Required = data["FMMInfo"]["Required"]; newMod.Location = path.Replace(".ini", ".fm"); try { newMod.Icon = bmIcon; } catch { newMod.Icon = null; } try { newMod.Image = bmImage; } catch { newMod.Image = null; } mMods.Add(newMod); })); } } }
/// <summary> /// Creates a binary patch (in <a href="http://www.daemonology.net/bsdiff/">bsdiff</a> format) that can be used /// (by <see cref="Apply"/>) to transform <paramref name="oldData"/> into <paramref name="newData"/>. /// </summary> /// <param name="oldData">The original binary data.</param> /// <param name="newData">The new binary data.</param> /// <param name="output">A <see cref="Stream"/> to which the patch will be written.</param> public static void Create(byte[] oldData, byte[] newData, Stream output) { // check arguments if (oldData == null) throw new ArgumentNullException("oldData"); if (newData == null) throw new ArgumentNullException("newData"); if (output == null) throw new ArgumentNullException("output"); if (!output.CanSeek) throw new ArgumentException("Output stream must be seekable.", "output"); if (!output.CanWrite) throw new ArgumentException("Output stream must be writable.", "output"); /* Header is 0 8 "BSDIFF40" 8 8 length of bzip2ed ctrl block 16 8 length of bzip2ed diff block 24 8 length of new file */ /* File is 0 32 Header 32 ?? Bzip2ed ctrl block ?? ?? Bzip2ed diff block ?? ?? Bzip2ed extra block */ byte[] header = new byte[c_headerSize]; WriteInt64(c_fileSignature, header, 0); // "BSDIFF40" WriteInt64(0, header, 8); WriteInt64(0, header, 16); WriteInt64(newData.Length, header, 24); long startPosition = output.Position; output.Write(header, 0, header.Length); int[] I = SuffixSort(oldData); byte[] db = new byte[newData.Length + 1]; byte[] eb = new byte[newData.Length + 1]; int dblen = 0; int eblen = 0; using (WrappingStream wrappingStream = new WrappingStream(output, Ownership.None)) using (BZip2OutputStream bz2Stream = new BZip2OutputStream(wrappingStream)) { // compute the differences, writing ctrl as we go int scan = 0; int pos = 0; int len = 0; int lastscan = 0; int lastpos = 0; int lastoffset = 0; while (scan < newData.Length) { int oldscore = 0; for (int scsc = scan += len; scan < newData.Length; scan++) { len = Search(I, oldData, newData, scan, 0, oldData.Length, out pos); for (; scsc < scan + len; scsc++) { if ((scsc + lastoffset < oldData.Length) && (oldData[scsc + lastoffset] == newData[scsc])) oldscore++; } if ((len == oldscore && len != 0) || (len > oldscore + 8)) break; if ((scan + lastoffset < oldData.Length) && (oldData[scan + lastoffset] == newData[scan])) oldscore--; } if (len != oldscore || scan == newData.Length) { int s = 0; int sf = 0; int lenf = 0; for (int i = 0; (lastscan + i < scan) && (lastpos + i < oldData.Length); ) { if (oldData[lastpos + i] == newData[lastscan + i]) s++; i++; if (s * 2 - i > sf * 2 - lenf) { sf = s; lenf = i; } } int lenb = 0; if (scan < newData.Length) { s = 0; int sb = 0; for (int i = 1; (scan >= lastscan + i) && (pos >= i); i++) { if (oldData[pos - i] == newData[scan - i]) s++; if (s * 2 - i > sb * 2 - lenb) { sb = s; lenb = i; } } } if (lastscan + lenf > scan - lenb) { int overlap = (lastscan + lenf) - (scan - lenb); s = 0; int ss = 0; int lens = 0; for (int i = 0; i < overlap; i++) { if (newData[lastscan + lenf - overlap + i] == oldData[lastpos + lenf - overlap + i]) s++; if (newData[scan - lenb + i] == oldData[pos - lenb + i]) s--; if (s > ss) { ss = s; lens = i + 1; } } lenf += lens - overlap; lenb -= lens; } for (int i = 0; i < lenf; i++) db[dblen + i] = (byte)(newData[lastscan + i] - oldData[lastpos + i]); for (int i = 0; i < (scan - lenb) - (lastscan + lenf); i++) eb[eblen + i] = newData[lastscan + lenf + i]; dblen += lenf; eblen += (scan - lenb) - (lastscan + lenf); byte[] buf = new byte[8]; WriteInt64(lenf, buf, 0); bz2Stream.Write(buf, 0, 8); WriteInt64((scan - lenb) - (lastscan + lenf), buf, 0); bz2Stream.Write(buf, 0, 8); WriteInt64((pos - lenb) - (lastpos + lenf), buf, 0); bz2Stream.Write(buf, 0, 8); lastscan = scan - lenb; lastpos = pos - lenb; lastoffset = pos - scan; } } } // compute size of compressed ctrl data long controlEndPosition = output.Position; WriteInt64(controlEndPosition - startPosition - c_headerSize, header, 8); // write compressed diff data using (WrappingStream wrappingStream = new WrappingStream(output, Ownership.None)) using (BZip2OutputStream bz2Stream = new BZip2OutputStream(wrappingStream)) { bz2Stream.Write(db, 0, dblen); } // compute size of compressed diff data long diffEndPosition = output.Position; WriteInt64(diffEndPosition - controlEndPosition, header, 16); // write compressed extra data using (WrappingStream wrappingStream = new WrappingStream(output, Ownership.None)) using (BZip2OutputStream bz2Stream = new BZip2OutputStream(wrappingStream)) { bz2Stream.Write(eb, 0, eblen); } // seek to the beginning, write the header, then seek back to end long endPosition = output.Position; output.Position = startPosition; output.Write(header, 0, header.Length); output.Position = endPosition; }