本文整理汇总了C#中Windows.Storage.Streams.InMemoryRandomAccessStream.AsStream方法的典型用法代码示例。如果您正苦于以下问题:C# InMemoryRandomAccessStream.AsStream方法的具体用法?C# InMemoryRandomAccessStream.AsStream怎么用?C# InMemoryRandomAccessStream.AsStream使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Windows.Storage.Streams.InMemoryRandomAccessStream
的用法示例。
在下文中一共展示了InMemoryRandomAccessStream.AsStream方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SaveResultToCameraRollAsync
/// <summary>
/// Asynchronously saves the <paramref name="photo" /> given to the camera roll album.
/// </summary>
/// <param name="photo">Photo to save.</param>
/// <returns>Image with thumbnail.</returns>
/// <exception cref="ArgumentNullException"><paramref name="photo"/> is <see langword="null"/>.</exception>
public async Task<IThumbnailedImage> SaveResultToCameraRollAsync(ICapturedPhoto photo)
{
if (photo == null)
{
throw new ArgumentNullException("photo");
}
Tracing.Trace("StorageService: Trying to save picture to the Camera Roll.");
Picture cameraRollPicture;
string name = this.GeneratePhotoName();
using (InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream())
{
// Convert image to JPEG format and rotate in accordance with the original photo orientation.
Tracing.Trace("StorageService: Converting photo to JPEG format. Size: {0}x{1}, Rotation: {2}", photo.Width, photo.Height, photo.Rotation);
byte[] pixelData = await photo.DetachPixelDataAsync();
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
encoder.BitmapTransform.Rotation = photo.Rotation;
encoder.BitmapTransform.Flip = photo.Flip;
encoder.IsThumbnailGenerated = true;
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, photo.Width, photo.Height, Constants.DefaultDpiX, Constants.DefaultDpiY, pixelData);
await encoder.FlushAsync();
cameraRollPicture = this.lazyMediaLibrary.Value.SavePictureToCameraRoll(name, stream.AsStream());
}
Tracing.Trace("StorageService: Saved to Camera Roll as {0}", name);
return new MediaLibraryThumbnailedImage(cameraRollPicture);
}
示例2: FromStream
internal static Bitmap FromStream(Stream stream)
{
Bitmap bitmap = null;
Task.Run(async () =>
{
using (var raStream = new InMemoryRandomAccessStream())
{
await stream.CopyToAsync(raStream.AsStream());
var decoder = await BitmapDecoder.CreateAsync(raStream);
var pixelData = await decoder.GetPixelDataAsync();
var width = (int)decoder.OrientedPixelWidth;
var height = (int)decoder.OrientedPixelHeight;
const PixelFormat format = PixelFormat.Format32bppArgb;
var bytes = pixelData.DetachPixelData();
bitmap = new Bitmap(width, height, format);
var data = bitmap.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, format);
Marshal.Copy(bytes, 0, data.Scan0, bytes.Length);
bitmap.UnlockBits(data);
}
}).Wait();
return bitmap;
}
示例3: manager_DataRequested
void manager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
{
// do the basics...
var data = args.Request.Data;
data.Properties.Title = "Deferred image";
data.Properties.Description = "I'll have to be downloaded first!";
// get a deferral...
data.SetDataProvider(StandardDataFormats.Bitmap, async (request) =>
{
var deferral = request.GetDeferral();
try
{
// download...
using (var inStream = await new HttpClient().GetStreamAsync("http://streetfoo.apphb.com/images/graffiti00.jpg"))
{
// copy the stream... but we'll need to obtain a facade
// to map between WinRT and .NET...
var outStream = new InMemoryRandomAccessStream();
inStream.CopyTo(outStream.AsStream());
// send that...
var reference = RandomAccessStreamReference.CreateFromStream(outStream);
request.SetData(reference);
}
}
finally
{
deferral.Complete();
}
});
}
示例4: AsRandomAccessStream
public static IRandomAccessStream AsRandomAccessStream(this Stream stream)
{
// This is bad, as we are reading the whole input stream in memory, but better than nothing.
var randomStream = new InMemoryRandomAccessStream();
stream.CopyTo(randomStream.AsStream());
randomStream.Seek(0);
return randomStream;
}
示例5: Run
private async void Run()
{
await _HubConnection.Start();
var cam = new MediaCapture();
await cam.InitializeAsync(new MediaCaptureInitializationSettings()
{
MediaCategory = MediaCategory.Media,
StreamingCaptureMode = StreamingCaptureMode.Video
});
_Sensor.MotionDetected += async (int pinNum) =>
{
var stream = new InMemoryRandomAccessStream();
Stream imageStream = null;
try
{
await Task.Factory.StartNew(async () =>
{
_Sensor.IsActive = false;
await cam.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
stream.Seek(0);
imageStream = stream.AsStream();
imageStream.Seek(0, SeekOrigin.Begin);
string imageUrl = await NotificationHelper.UploadImageAsync(imageStream);
switch (await OxfordHelper.IdentifyAsync(imageUrl))
{
case AuthenticationResult.IsOwner:
// open the door
MotorController.PWM(26);
break;
case AuthenticationResult.Unkown:
// send notification to the owner
NotificationHelper.NotifyOwnerAsync(imageUrl);
break;
case AuthenticationResult.None:
default:
break;
}
_Sensor.IsActive = true;
});
}
finally
{
if (stream != null)
stream.Dispose();
if (imageStream != null)
imageStream.Dispose();
}
};
}
示例6: EncodeFromByte
public static async Task<string> EncodeFromByte(byte[] image, uint height, uint width, double dpiX = 96, double dpiY = 96)
{
// encode image
var encoded = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, encoded);
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight, height, width, dpiX, dpiY, image);
await encoder.FlushAsync();
encoded.Seek(0);
// read bytes
var bytes = new byte[encoded.Size];
await encoded.AsStream().ReadAsync(bytes, 0, bytes.Length);
// create base64
return Convert.ToBase64String(bytes);
}
示例7: ScaleImageStreamAsync
/// <summary>
/// Scales the image in the given memory stream.
/// </summary>
/// <param name="originalStream">The original image stream to scale.</param>
/// <param name="originalResolutionWidth">The original width.</param>
/// <param name="originalResolutionHeight">The original height.</param>
/// <param name="scaledStream">Stream where the scaled image is stored.</param>
/// <param name="scaleWidth">The target width.</param>
/// <param name="scaleHeight">The target height.</param>
/// <returns></returns>
public static async Task ScaleImageStreamAsync(MemoryStream originalStream,
int originalResolutionWidth,
int originalResolutionHeight,
MemoryStream scaledStream,
int scaleWidth,
int scaleHeight)
{
System.Diagnostics.Debug.WriteLine(DebugTag + "ScaleImageStreamAsync() ->");
// Create a bitmap containing the full resolution image
var bitmap = new WriteableBitmap(originalResolutionWidth, originalResolutionHeight);
originalStream.Seek(0, SeekOrigin.Begin);
await bitmap.SetSourceAsync(originalStream.AsRandomAccessStream());
/* Construct a JPEG encoder with the newly created
* InMemoryRandomAccessStream as target
*/
IRandomAccessStream previewResolutionStream = new InMemoryRandomAccessStream();
previewResolutionStream.Size = 0;
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(
BitmapEncoder.JpegEncoderId, previewResolutionStream);
// Copy the full resolution image data into a byte array
Stream pixelStream = bitmap.PixelBuffer.AsStream();
var pixelArray = new byte[pixelStream.Length];
await pixelStream.ReadAsync(pixelArray, 0, pixelArray.Length);
// Set the scaling properties
encoder.BitmapTransform.ScaledWidth = (uint)scaleWidth;
encoder.BitmapTransform.ScaledHeight = (uint)scaleHeight;
encoder.BitmapTransform.InterpolationMode = BitmapInterpolationMode.Fant;
encoder.IsThumbnailGenerated = true;
// Set the image data and the image format setttings to the encoder
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
(uint)originalResolutionWidth, (uint)originalResolutionHeight,
96.0, 96.0, pixelArray);
await encoder.FlushAsync();
previewResolutionStream.Seek(0);
await previewResolutionStream.AsStream().CopyToAsync(scaledStream);
System.Diagnostics.Debug.WriteLine(DebugTag + "<- ScaleImageStreamAsync()");
}
示例8: ResizeImage
public async Task<PortableImage> ResizeImage(PortableImage image, int newWidth, int newHeight)
{
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(((Stream)image.EncodedData).AsRandomAccessStream());
var memoryRandomAccessStream = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateForTranscodingAsync(memoryRandomAccessStream, decoder);
encoder.BitmapTransform.ScaledHeight = (uint)newHeight;
encoder.BitmapTransform.ScaledWidth = (uint)newWidth;
//var bounds = new BitmapBounds();
//bounds.Height = 50;
//bounds.Width = 50;
//bounds.X = 50;
//bounds.Y = 50;
//enc.BitmapTransform.Bounds = bounds;
try
{
await encoder.FlushAsync();
}
catch (Exception exc)
{
var message = "Error on resizing the image: ";
if (exc.Message != null)
message += exc.Message;
throw new Exception(message);
}
//var writeableBitmap = new WriteableBitmap(newWidth, newHeight);
//writeableBitmap.SetSourceAsync(memoryRandomAccessStream);
memoryRandomAccessStream.Seek(0);
return new PortableImage
{
Width = newWidth,
Height = newHeight,
EncodedData = memoryRandomAccessStream.AsStream()
};
}
示例9: play
private void play(double note)
{
MediaElement playback = new MediaElement();
IRandomAccessStream stream = new InMemoryRandomAccessStream();
BinaryWriter writer = new BinaryWriter(stream.AsStream());
int formatChunkSize = 16;
int headerSize = 8;
short formatType = 1;
short tracks = 1;
int samplesPerSecond = 44100;
short bitsPerSample = 16;
short frameSize = (short)(tracks * ((bitsPerSample + 7) / 8));
int bytesPerSecond = samplesPerSecond * frameSize;
int waveSize = 4;
int data = 0x61746164;
int samples = 88200 * 4;
int dataChunkSize = samples * frameSize;
int fileSize = waveSize + headerSize + formatChunkSize + headerSize + dataChunkSize;
double frequency = note * 1.5;
writer.Write(0x46464952); // RIFF
writer.Write(fileSize);
writer.Write(0x45564157); // WAVE
writer.Write(0x20746D66); // Format
writer.Write(formatChunkSize);
writer.Write(formatType);
writer.Write(tracks);
writer.Write(samplesPerSecond);
writer.Write(bytesPerSecond);
writer.Write(frameSize);
writer.Write(bitsPerSample);
writer.Write(data);
writer.Write(dataChunkSize);
for (int i = 0; i < samples / 4; i++)
{
double t = (double)i / (double)samplesPerSecond;
short s = (short)(10000 * (Math.Sin(t * frequency * 2.0 * Math.PI)));
writer.Write(s);
}
stream.Seek(0);
playback.SetSource(stream, "audio/wav");
playback.Play();
}
示例10: btnTakePhoto_Click
private async void btnTakePhoto_Click(object sender, RoutedEventArgs e)
{
btnTakePhoto.IsEnabled = false;
btnStartPreview.IsEnabled = false;
InMemoryRandomAccessStream stream = new InMemoryRandomAccessStream();
await mediaCapture.CapturePhotoToStreamAsync(ImageEncodingProperties.CreateJpeg(), stream);
stream.Seek(0);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(stream);
captureImage.Source = bitmap;
stream.Seek(0);
Stream st = stream.AsStream();
if (isPreviewing == true) await mediaCapture.StopPreviewAsync();
isPreviewing = false;
previewElement.Visibility = Visibility.Collapsed;
progring.IsActive = true;
try
{
EmotionServiceClient emotionServiceClient =
new EmotionServiceClient("12345678901234567890123456789012");
// replace 12345678901234567890123456789012 with your key taken from https://www.projectoxford.ai/Subscription/
emotionResult = await emotionServiceClient.RecognizeAsync(st);
}
catch { }
progring.IsActive = false;
if ((emotionResult != null) && (emotionResult.Length > 0))
{
emo.Clear();
emo.Add(emotionResult[0]);
this.DataContext = emo.ElementAt(0);
}
btnStartPreview.IsEnabled = true;
btnTakePhoto.IsEnabled = true;
}
示例11: DetectPhotoAsync
private async Task DetectPhotoAsync(IRandomAccessStream stream, PhotoOrientation photoOrientation)
{
using (var inputStream = stream)
{
var decoder = await BitmapDecoder.CreateAsync(inputStream);
var file = await KnownFolders.PicturesLibrary.CreateFileAsync("SimplePhoto.jpeg", CreationCollisionOption.GenerateUniqueName);
using (var outputStream = new InMemoryRandomAccessStream())
{
var encoder = await BitmapEncoder.CreateForTranscodingAsync(outputStream, decoder);
var properties = new BitmapPropertySet { { "System.Photo.Orientation", new BitmapTypedValue(photoOrientation, PropertyType.UInt16) } };
await encoder.BitmapProperties.SetPropertiesAsync(properties);
await encoder.FlushAsync();
var faces = await _instance.DetectAsync(outputStream.AsStream(), false, true, true, false);
}
}
}
示例12: StartRecordingToStreamAsync
/// <summary>
/// Start recording a new video and save it as stream.
/// </summary>
/// <param name="encoding">The video encoding. Mp4 by default.</param>
/// <returns>The <see cref="VideoCaptureStreamResult"/> struct.</returns>
public async Task<VideoCaptureStreamResult> StartRecordingToStreamAsync(VideoEncoding encoding)
{
if (!this.isInitialized)
{
Debug.WriteLine("First you need to initialize the videocapturemanager.");
return new VideoCaptureStreamResult();
}
if (this.IsRecording)
{
Debug.WriteLine("VideoCapture is already recording. Call Stop before Start again.");
return new VideoCaptureStreamResult(false, Stream.Null);
}
try
{
Debug.WriteLine("Recording video...");
MediaEncodingProfile encodingProfile;
switch (encoding)
{
case VideoEncoding.AVI:
encodingProfile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
break;
case VideoEncoding.WMV:
encodingProfile = MediaEncodingProfile.CreateWmv(VideoEncodingQuality.Auto);
break;
default:
case VideoEncoding.MP4:
encodingProfile = MediaEncodingProfile.CreateAvi(VideoEncodingQuality.Auto);
break;
}
var stream = new InMemoryRandomAccessStream();
await this.mediaCapture.StartRecordToStreamAsync(encodingProfile, stream);
this.isRecording = true;
return new VideoCaptureStreamResult(true, stream.AsStream());
}
catch (Exception ex)
{
Debug.WriteLine("Exception when recording a video: " + ex.ToString());
return new VideoCaptureStreamResult(false, Stream.Null);
}
}
示例13: TakePhotoToStreamAsync
/// <summary>
/// Take a new photo and hold it in the output stream.
/// </summary>
/// <param name="parameters">The set of parameters used to take the photo, <see cref="ICameraResolution"/> class.</param>
/// <param name="format">The image format. <see cref="PhotoCaptureFormat"/> enum. </param>
/// <returns>The <see cref="PhotoCaptureStreamResult"/> struct.</returns>
public async Task<PhotoCaptureStreamResult> TakePhotoToStreamAsync(ICameraResolution parameters, PhotoCaptureFormat format)
{
if (!this.isInitialized)
{
Debug.WriteLine("First you need to initialize the videocapturemanager.");
return new PhotoCaptureStreamResult();
}
try
{
if (parameters != null)
{
Debug.WriteLine("Applying paramenters...");
await this.mediaCapture.VideoDeviceController.SetMediaStreamPropertiesAsync(MediaStreamType.Photo, (parameters as StreamResolution).EncodingProperties);
}
Debug.WriteLine("Taking photo...");
var stream = new InMemoryRandomAccessStream();
var properties = this.GetImageEncodingProperties(format);
await this.mediaCapture.CapturePhotoToStreamAsync(properties, stream);
Debug.WriteLine("Photo stream loaded.");
return new PhotoCaptureStreamResult(true, stream.AsStream());
}
catch (Exception ex)
{
Debug.WriteLine("Exception when taking a photo: " + ex.ToString());
return new PhotoCaptureStreamResult(false, Stream.Null);
}
}
示例14: ResizeImage
/// <summary>
/// resizes the image so it can go through VMHub processing
/// </summary>
/// <param name="ms"></param>
/// <param name="maxImageSize"></param>
/// <returns></returns>
async private Task<byte[]> ResizeImage(MemoryStream ms, uint maxImageSize)
{
MemoryStream temp = ms;
IRandomAccessStream ras = temp.AsRandomAccessStream();
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(ras).AsTask().ConfigureAwait(false);
uint w = decoder.PixelWidth, h = decoder.PixelHeight;
if (w > maxImageSize || h > maxImageSize)
{
if (w > h)
{
w = maxImageSize;
h = decoder.PixelHeight * maxImageSize / decoder.PixelWidth;
}
else
{
w = decoder.PixelWidth * maxImageSize / decoder.PixelHeight;
h = maxImageSize;
}
}
BitmapTransform transform = new BitmapTransform() { ScaledHeight = h, ScaledWidth = w };
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(
BitmapPixelFormat.Rgba8,
BitmapAlphaMode.Premultiplied,
transform,
ExifOrientationMode.RespectExifOrientation,
ColorManagementMode.DoNotColorManage);
byte[] pixels = pixelData.DetachPixelData();
InMemoryRandomAccessStream encoded = new InMemoryRandomAccessStream();
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, encoded);
encoder.SetPixelData(BitmapPixelFormat.Rgba8, BitmapAlphaMode.Premultiplied, w, h, 96, 96, pixels);
await encoder.FlushAsync().AsTask().ConfigureAwait(false);
encoded.Seek(0);
byte[] outBytes = new byte[encoded.Size];
await encoded.AsStream().ReadAsync(outBytes, 0, outBytes.Length);
return outBytes;
}
示例15: RenderToBase64
public async Task<string> RenderToBase64(UIElement element)
{
RenderTargetBitmap rtb = new RenderTargetBitmap();
await rtb.RenderAsync(element);
var pixelBuffer = await rtb.GetPixelsAsync();
var pixels = pixelBuffer.ToArray();
// Useful for rendering in the correct DPI
var displayInformation = DisplayInformation.GetForCurrentView();
var stream = new InMemoryRandomAccessStream();
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
encoder.SetPixelData(BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Premultiplied,
(uint)rtb.PixelWidth,
(uint)rtb.PixelHeight,
displayInformation.RawDpiX,
displayInformation.RawDpiY,
pixels);
await encoder.FlushAsync();
stream.Seek(0);
// read bytes
var bytes = new byte[stream.Size];
await stream.AsStream().ReadAsync(bytes, 0, bytes.Length);
// create base64
return Convert.ToBase64String(bytes);
}