Add text to picture in Windows Universal app - mobile

I have universal app created for Win 10 mobile which captures photo. I want to add stamp (some text) to my photo. Is it possible? It seems working with bitmap is really difficult in universal applications

Check this link:
How to add wartermark text/image to a bitmap in Windows Store app
Or better use Win2D library (you can find it on NuGet) and snippet like this:
CanvasDevice device = CanvasDevice.GetSharedDevice();
CanvasRenderTarget offscreen = new CanvasRenderTarget(device, 500, 500, 96);
cbi = await CanvasBitmap.LoadAsync(device, "mydog.jpg");
using (var ds = offscreen.CreateDrawingSession())
{
ds.DrawImage(cbi);
var format = new CanvasTextFormat()
{
FontSize = 24,
HorizontalAlignment = CanvasHorizontalAlignment.Left,
VerticalAlignment = CanvasVerticalAlignment.Top,
WordWrapping = CanvasWordWrapping.Wrap,
FontFamily = "Tahoma"
};
var tl = new CanvasTextLayout(ds, "Some text", format, 200, 50); // width 200 and height 50
ds.DrawTextLayout(tl, 10, 10, Colors.Black);
tl.Dispose();
}
using (var stream = new InMemoryRandomAccessStream())
{
stream.Seek(0);
await offscreen.SaveAsync(stream, CanvasBitmapFileFormat.Png);
BitmapImage image = new BitmapImage();
image.SetSource(stream);
img.Source = image;
}

Related

How to get accessible camera resolutions?

I would like to ask, how it is possible to get all accessible camera resolutions in Windows Phone 8.1 app (for both silverlight and WinRT). I wanted to use:
Windows.Phone.Media.Capture.PhotoCaptureDevice.GetAvailableCaptureResolutions(
Windows.Phone.Media.Capture.CameraSensorLocation.Back);
But I am getting message that namespace Windows.Phone.Media.Capture is obsolete and may not be supported from next version of Windows Phone starting with Windows Phone Blue and that I should use Windows.Media.Capture instead. However Windows.Media.Capture does not allow me to get accessible camera resolutions, so I would like to ask, how to solve this.
Thank you.
It can be done like this:
First let's define method to get Device ID which will be used to take a photo:
private static async Task<DeviceInformation> GetCameraID(Windows.Devices.Enumeration.Panel desiredCamera)
{
DeviceInformation deviceID = (await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture))
.FirstOrDefault(x => x.EnclosureLocation != null && x.EnclosureLocation.Panel == desiredCamera);
if (deviceID != null) return deviceID;
else throw new Exception(string.Format("Camera of type {0} doesn't exist.", desiredCamera));
}
Then after we initialize the camera - we can read the resolutions like this:
private async void InitCameraBtn_Click(object sender, RoutedEventArgs e)
{
var cameraID = await GetCameraID(Windows.Devices.Enumeration.Panel.Back);
captureManager = new MediaCapture();
await captureManager.InitializeAsync(new MediaCaptureInitializationSettings
{
StreamingCaptureMode = StreamingCaptureMode.Video,
PhotoCaptureSource = PhotoCaptureSource.VideoPreview,
AudioDeviceId = string.Empty,
VideoDeviceId = cameraID.Id
});
// Get resolutions
var resolutions = captureManager.VideoDeviceController.GetAvailableMediaStreamProperties(MediaStreamType.Photo).Select(x => x as VideoEncodingProperties).ToList();
// get width and height:
uint width = resolutions[0].Width;
uint height = resolutions[0].Height;
}

Actionscript 3, Flash CC: Placing Objects In An Array From The Library Onto The Stage

Hello programming gurus of stackoverflow, I am hoping that at least one of you will be able to help me with my coding problem. This is the first time I'm posting on this site, so if I miss something with the structure of my post, or anything please let me know (preferably not in a condescending matter) and I will gladly change it.
I actually had a different problem I was going to ask about, but I recently realized that some objects from my library weren't showing up on my stage. Hopefully, if this gets solved I won't have my other problem.
I am creating a learning module app using Flash CC and Actionscript 3, I like to think I am fairly proficient with Flash, but right now all my code is on the timeline because when I started I wasn't aware of the package setup. When I finish with the learning module I'll try and move everything to an AS package, so please bear with me.
This current frame of the module is a drag and drop game where the user drags the correct food, for the animal they chose in the previous frame, to the animal in the middle. The animal is dynamically placed on the stage, as well as an array of six possible food choices, all MovieClips pulled from the library. The array of food elements is actually not what I'm having problem with, they appear on my stage with no problems at all. The problem I'm having is when the user drags the correct food onto the animal, and the win condition is met, the array of balloon elements does not show up on the stage. I find it weird because I'm using near identical code for both the food and balloon array.
Here is my full code:
import flash.display.MovieClip;
import flash.events.MouseEvent;
foodPet();
function foodPet():void {
//all of my pet, food, and balloon library objects have been exported for AS
var theBird:pet_bird = new pet_bird;
var theCat:pet_cat = new pet_cat;
var theChicken:pet_chicken = new pet_chicken;
var theDog:pet_dog = new pet_dog;
var theDuck:pet_duck = new pet_duck;
var theGuinea:pet_guinea = new pet_guinea;
var theHamster:pet_hamster = new pet_hamster;
var birdSeed:food_bird_seed = new food_bird_seed;
var catFood:food_cat_food = new food_cat_food;
var chickenFeed:food_chicken_feed = new food_chicken_feed;
var chocolate:food_chocolate = new food_chocolate;
var dogFood:food_dog_food = new food_dog_food;
var duckFood:food_duck_food = new food_duck_food;
var animalList:Array = [theBird, theCat, theChicken, theDog,
theDuck, theGuinea, theHamster];
var food1Array:Array = [birdSeed, catFood, chickenFeed,
chocolate, dogFood, duckFood, 4];
var xPosFood:Array = new Array();
var yPosFood:Array = new Array();
xPosFood = [32, 71, 146, 363, 431, 512];
yPosFood = [304, 222, 123, 123, 222, 304];
var animalClip:MovieClip;
animalClip = animalList[chosenAnimal];
addChild(animalClip);
animalClip.x = 256;
animalClip.y = 287;
animalClip.name = "selectedAnimal";
for (var i:uint = 0; i < food1Array.length - 1; i++){ //Where the food gets added
var isItRight:Boolean = false;
var foodName:String = ("food" + i);
var foodClip:MovieClip;
foodClip = food1Array[i];
foodClip.x = xPosFood[i];
foodClip.y = yPosFood[i];
foodClip.name = foodName;
addChild(foodClip);
trace(foodClip.parent);
foodDragSetup(foodClip, animalClip, food1Array[food1Array.length - 1], isItRight);
}
}
function foodDragSetup(clip:MovieClip, targ:MovieClip, correctNum:uint, isItRight:Boolean) {
var beingDragged:Boolean = false;
var xPos:Number = clip.x;
var yPos:Number = clip.y;
clip.addEventListener(MouseEvent.MOUSE_DOWN, beginDrag);
function beginDrag(event:MouseEvent):void
{
clip.startDrag();
if (int(clip.name.substr(4)) == correctNum){
isItRight = true;
}
this.beingDragged = true;
setChildIndex(clip, numChildren - 1);
clip.addEventListener(MouseEvent.MOUSE_UP, endDrag);
}
function endDrag(event:MouseEvent):void
{
if (this.beingDragged) {
this.beingDragged = false;
clip.stopDrag();
if ((isItRight) && (clip.hitTestPoint(targ.x, targ.y, true))){
trace(targ.name + " has been hit.");
clip.x = targ.x;
clip.y = targ.y;
win_animal_food();
} else {
isItRight = false;
clip.x = xPos;
clip.y = yPos;
}
}
}
}
function win_animal_food():void {
const BALLOON_ROW:int = 4;
var count:uint = 0;
var altX:uint = 0;
var bBalloon:blue_balloon = new blue_balloon;
var gBalloon:green_balloon = new green_balloon;
var oBalloon:orange_balloon = new orange_balloon;
var pBalloon:purple_balloon = new purple_balloon;
var rBalloon:red_balloon = new red_balloon;
var yBalloon:yellow_balloon = new yellow_balloon;
var balloonList:Array = [bBalloon, gBalloon, oBalloon,
pBalloon, rBalloon, yBalloon, bBalloon, gBalloon,
oBalloon, pBalloon, rBalloon, yBalloon, bBalloon,
gBalloon, oBalloon, pBalloon];
var balloonY:Array = [144, -205, -265, -325];
var balloonX:Array = [0, 140, 284, 428, 68, 212, 356, 500];
for (var ballY:uint = 0; ballY < balloonY.length; ballY++){ //Where balloons
for (var ballX:uint = altX; ballX < altX + BALLOON_ROW; ballX++){ //get added
var balloonName:String = ("balloon" + count);
var balloonClip:MovieClip;
balloonClip = balloonList[count];
balloonClip.x = balloonX[ballX];
balloonClip.y = balloonY[ballY];
balloonClip.name = balloonName;
addChild(balloonClip);
trace(balloonClip.parent);
trace(balloonClip + " has been added!");
balloonClip.addEventListener(MouseEvent.CLICK, balloonPop);
count++;
}
if (altX == 0) {
altX = BALLOON_ROW;
} else {
altX = 0;
}
}
function balloonPop(event:MouseEvent):void {
event.target.play();
event.target.removeEventListener(MouseEvent.CLICK, balloonPop);
}
}
I thought there might have been a problem with my balloon MovieClips, so I subbed them in the food array:
var birdSeed:blue_balloon = new blue_balloon;
var catFood:green_balloon = new green_balloon;
var chickenFeed:orange_balloon = new orange_balloon;
var chocolate:purple_balloon = new purple_balloon;
var dogFood:red_balloon = new red_balloon;
var duckFood:yellow_balloon = new yellow_balloon;
They all showed up on the stage, so there's nothing wrong with the MovieClips.
Added: The first values of balloonXArray and balloonYArray were originally -4 and -145 respectively, but when I started having problems I wanted to make sure the balloons were showing up so I set the first values to 0 and 144 the balloon height and width are both 144 and their cross (not sure on it's name) is in the top left corner.
Added: The reason why there are multiple instances of the same balloon in the balloonList is because I need four rows of four balloons, but only have six different balloons.
I know the balloons are on the stage because the debug display shows their x and y values on the viewable stage. Using trace(foodClip.parent) and trace(balloonClip.parent) shows that the balloons and food all have the same parent, MainTimeline, so I know the balloons aren't getting added to some different space.
I have searched online, but have not come across anyone with a similar problem. Thus, I am asking on this forum if anyone can tell me why my balloons will not show up on the stage.
Please and thank you.
One thing I see straight off in the baloonList is that you have the same object instances listed multiple times. Each instance can only exist on stage exactly once. If you addChild() an instance that is already on stage, the instance is first removed, then re-added at the top of the display list.
You should change:
var bBalloon:blue_balloon = new blue_balloon;
var gBalloon:green_balloon = new green_balloon;
var oBalloon:orange_balloon = new orange_balloon;
var pBalloon:purple_balloon = new purple_balloon;
var rBalloon:red_balloon = new red_balloon;
var yBalloon:yellow_balloon = new yellow_balloon;
var balloonList:Array = [bBalloon, gBalloon, oBalloon,
pBalloon, rBalloon, yBalloon, bBalloon, gBalloon,
oBalloon, pBalloon, rBalloon, yBalloon, bBalloon,
gBalloon, oBalloon, pBalloon];
to:
var balloonList:Array = [
new blue_balloon,
new green_balloon,
new orange_balloon,
new purple_balloon,
new red_balloon,
new yellow_balloon,
new blue_balloon,
new green_balloon,
new orange_balloon,
new purple_balloon,
new red_balloon,
new yellow_balloon,
new blue_balloon,
new blue_balloon,
new green_balloon,
new orange_balloon,
new purple_balloon
];

How to get size of bitmapdata converted into bytearray

I have bitmapdata object converted to bytearray:
var bytes:ByteArray = bitmapDataA.getPixels(bitmapDataA.rect);
and I save it as .jpg file for later:
writeStream.writeBytes(bytes, 0, bytes.bytesAvailable);
Now, when I want to retrieve the data:
var file:File = File.documentsDirectory.resolvePath("data/"+photoNameVec[loadCounter]);
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var fileContent:ByteArray = new ByteArray;
fileStream.readBytes(fileContent);
fileStream.close();
var bmpData:BitmapData = new BitmapData(XXX, YYY);
bmpData.setPixels(bmpData.rect, fileContent);
addChild(new Bitmap(bmpData));
But I need to get exact XXX and YYY to show the graphics correctly. How can I do this?
EDIT:
As there was no way to determine bitmapdata width and height based on bytearray, I decided to transform all pictures I take to 1024px x 768px:
var bitmapDataA:BitmapData = new BitmapData(mpLoaderInfo.width, mpLoaderInfo.height);
var matrix:Matrix = new Matrix();
matrix.scale( 1024 / mpLoaderInfo.width, 768 / mpLoaderInfo.height);
var bitmapDataB:BitmapData = new BitmapData(1024,768);
bitmapDataB.draw(mpLoaderInfo.content, matrix, null, null, new Rectangle(0,0,1024,768), true);
Still waiting for tips on getting Width x Height from bytearray created by getPixels method of bitmapdata.
You can use a Loader class to load the image then you can access it's width/height and BitmapData
var file:File = File.documentsDirectory.resolvePath("data/"+photoNameVec[loadCounter]);
var myImage:BitmapData;
var loader:Loader = new Loader();
var urlReq:URLRequest = new URLRequest(file.url);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
loader.load(urlReq);
function loaded(e:Event):void
{
var bmp:Bitmap = e.target.content as Bitmap;
myImage = bmp.bitmapData;
trace(myImage.width, myImage.height);
}
And here is with loadBytes
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.INIT, loaded);
loader.loadBytes(yourByteArray);
function loaded(e:Event):void
{
var bmp:Bitmap = e.target.content as Bitmap;
myImage = bmp.bitmapData;
trace(myImage.width, myImage.height);
}
I guess that's the most suiting solution :)
Simply expand the the bytearray with extra values from which I shall gather width and height.
http://www.ghostwire.com/blog/archives/as3-serializing-bitmaps-storing-bitmapdata-as-raw-binarybytearray/
Ps.: Creating and reading uncompressed files is way faster than making png/jpg
The byte array created by getPixels does not contain any information on the height or width of the bitmap, it's simply an "unsigned integer (a 32-bit unmultiplied pixel value) for each pixel".
So you'll need to either write it as an image format (PNG/JPG) which will require encoding (hence time), or simply add the width and height to your byte array before writing to file.
Eg in your stream writer:
writeStream.writeInt( bitmapDataA.width );
writeStream.writeInt( bitmapDataA.height );
writeStream.writeBytes(bytes, 0, bytes.bytesAvailable);
Then when you are loading:
var file:File = File.documentsDirectory.resolvePath("data/"+photoNameVec[loadCounter]);
var fileStream:FileStream = new FileStream();
fileStream.open(file, FileMode.READ);
var w:int = fileStream.readInt();
var h:int = fileStream.readInt();
var fileContent:ByteArray = new ByteArray;
fileStream.readBytes(fileContent);
fileStream.close();
var bmpData:BitmapData = new BitmapData( w , h);
bmpData.setPixels(bmpData.rect, fileContent);
addChild(new Bitmap(bmpData));

ArcGIS Runtime for wpf - PointDataSource mapTip

I have GraphicsLayer in my application and I use PointDataSource like itemsSource:
trackEntryPointDataSource = new PointDataSource();
trackEntryPointDataSource.DataSpatialReference =
new SpatialReference((int)CommonEpsgCodes.JTSKEN);
trackEntryPointDataSource.XCoordinateBinding =
new System.Windows.Data.Binding("XJTSK");
trackEntryPointDataSource.YCoordinateBinding =
new System.Windows.Data.Binding("YJTSK");
SimpleRenderer srd = new SimpleRenderer();
srd.Symbol = new SimpleMarkerSymbol()
{
Color = new SolidColorBrush(Colors.Yellow)
};
EntriesLyr.GraphicsSource = trackEntryPointDataSource;
EntriesLyr.Renderer = srd;
Have someone any idea how to add MapTips to graphics symbols?
GraphicsLayer class has a MapTip property.
A detailed example if found here

How can I use NLog's RichTextBox Target in WPF application?

How can I use RichTextBox Target in WPF application?
I don't want to have a separate window with log, I want all log messages to be outputted in richTextBox located in WPF dialog.
I've tried to use WindowsFormsHost with RichTextBox box inside but that does not worked for me: NLog opened separate Windows Form anyway.
A workaround in the mean time is to use the 3 classes available here, then follow this procedure:
Import the 3 files into your project
If not already the case, use Project > Add Reference to add references to the WPF assemblies: WindowsBase, PresentationCore, PresentationFramework.
In WpfRichTextBoxTarget.cs, replace lines 188-203 with:
//this.TargetRichTextBox.Invoke(new DelSendTheMessageToRichTextBox(this.SendTheMessageToRichTextBox), new object[] { logMessage, matchingRule });
if (System.Windows.Application.Current.Dispatcher.CheckAccess() == false) {
System.Windows.Application.Current.Dispatcher.Invoke(new Action(() => {
SendTheMessageToRichTextBox(logMessage, matchingRule);
}));
}
else {
SendTheMessageToRichTextBox(logMessage, matchingRule);
}
}
private static Color GetColorFromString(string color, Brush defaultColor) {
if (defaultColor == null) return Color.FromRgb(255, 255, 255); // This will set default background colour to white.
if (color == "Empty") {
return (Color)colorConverter.ConvertFrom(defaultColor);
}
return (Color)colorConverter.ConvertFromString(color);
}
In your code, configure the new target like this below example:
I hope it helps, but it definitely does not seem to be a comprehensive implementation...
public void loading() {
var target = new WpfRichTextBoxTarget();
target.Name = "console";
target.Layout = "${longdate:useUTC=true}|${level:uppercase=true}|${logger}::${message}";
target.ControlName = "rtbConsole"; // Name of the richtextbox control already on your window
target.FormName = "MonitorWindow"; // Name of your window where there is the richtextbox, but it seems it will not really be taken into account, the application mainwindow will be used instead.
target.AutoScroll = true;
target.MaxLines = 100000;
target.UseDefaultRowColoringRules = true;
AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper();
asyncWrapper.Name = "console";
asyncWrapper.WrappedTarget = target;
SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);
}
If you define a RichTextBoxTarget in the config file, a new form is automatically created. This is because NLog initializes before your (named) form and control has been created. Even if you haven't got any rules pointing to the target. Perhaps there is a better solution, but I solved it by creating the target programatically:
using NLog;
//[...]
RichTextBoxTarget target = new RichTextBoxTarget();
target.Name = "RichTextBox";
target.Layout = "${longdate} ${level:uppercase=true} ${logger} ${message}";
target.ControlName = "textbox1";
target.FormName = "Form1";
target.AutoScroll = true;
target.MaxLines = 10000;
target.UseDefaultRowColoringRules = false;
target.RowColoringRules.Add(
new RichTextBoxRowColoringRule(
"level == LogLevel.Trace", // condition
"DarkGray", // font color
"Control", // background color
FontStyle.Regular
)
);
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Info", "ControlText", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "DarkRed", "Control"));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "White", "DarkRed", FontStyle.Bold));
target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "Yellow", "DarkRed", FontStyle.Bold));
AsyncTargetWrapper asyncWrapper = new AsyncTargetWrapper();
asyncWrapper.Name = "AsyncRichTextBox";
asyncWrapper.WrappedTarget = target;
SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);

Resources