Custom Android.Gms.Maps.Model.TileProvider issue with Constructor Arguments - c#

I have a Xaramin.Android project and I am trying to create a Custom TileProvider to use offline maps from mbtiles sqlite database and found an example that does what i want to do here https://github.com/antoniocarlon/MapUtils however this example is done in java so i started creating my own based on the above code but in Xamarin.Android in c#.
So i have created a Class MBTilesProvider that inherits from Android.Gms.Maps.Model.TileProvider however the : base(width, height) shows an error that 'TileProvider' does not contain a constructor that takes 2 arguments. I know that error is pretty self explanatory but i can't seem to find any documentation around what the constructor arguments are for TileProvider ? if i remove the :base from my class i get the error message that 'TileProvider' does not contain a constructor that contains 0 arguments.
public class MBTilesProvider : TileProvider
{
private int _width;
private int _height;
public MBTilesProvider(int width, int height) : base(width, height)
{
this._width = width;
this._height = height;
}
public Tile GetTile(int x, int y, int zoom)
{
y = tms2gmaps(y, zoom);
byte[] bitmap = RetreiveImage(x, y, zoom);
Tile tile = new Tile(_width, _height, bitmap);
return tile;
}
private byte[] RetreiveImage(int x, int y, int zoom)
{
byte[] image = null;
if(zoom > 0)
{
image = ReadImageFromDB(x, y, zoom);
if(image == null)
{
image = Crop(RetreiveImage(x / 2, y / 2, zoom - 1), x, y);
}
return image;
} else
{
return image;
}
}
private byte[] ReadImageFromDB(int x, int y, int zoom)
{
DataClient.MBTilesClient mBTilesClient = new DataClient.MBTilesClient();
return mBTilesClient.GetTile(x, y, zoom);
}
private int tms2gmaps(int y, int zoom)
{
int ymax = 1 << zoom;
return ymax - y - 1;
}
private byte[] Crop(byte[] image, int x, int y)
{
byte[] output = image;
if(image == null)
{
return output;
}
Bitmap bitmap = BitmapFactory.DecodeByteArray(image, 0, image.Length);
bitmap = Bitmap.CreateBitmap(
bitmap,
x % 2 == 0 ? 0 : bitmap.Width / 2,
y % 2 == 0 ? bitmap.Height / 2 : 0,
bitmap.Width,
bitmap.Height
);
var stream = new MemoryStream();
bitmap.Compress(Bitmap.CompressFormat.Png, 100, stream);
bitmap.Recycle();
output = stream.ToArray();
return output;
}
}
Any Help would be greatly appreciated.
Eddie

Use the ITileProvider interface instead of the TileProvider abstract class. Then you won't have issues with constructors.
public class MBTilesProvider : Java.Lang.Object, ITileProvider
I don't know why Xamarin creates both or how the abstract class should be used. I had the same issue, but this solved it for me. The Java.Lang.Object is so you don't have to override the Handle and Dispose methods.

Related

I Have a bug in my simple Lockbits Image class

I have this simple class to plot points on an image. It is limited to 24bbp. but at certain widths the image breaks, colors are distorted and the image moves towards the right the lower down in the image it gets. its only correct when the width is a multiple of 4 and I cant figure out why. can someone please point out my mistake? Thanks guys.
Example of problem
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using static System.Math;
public class TImage
{
private readonly Bitmap source = null;
private IntPtr Iptr = IntPtr.Zero;
private BitmapData bitmapData = null;
private bool locked = false;
private readonly int PixelCount;
private byte[] pixels;
public int Width { get; private set; }
public int Height { get; private set; }
public TImage(int width, int height)
{
source = new Bitmap(width, height, PixelFormat.Format24bppRgb);
Width = width; Height = height;
PixelCount = Width * Height;
}
public TImage(Bitmap image)
{
if (image.PixelFormat != PixelFormat.Format24bppRgb) throw new FormatException("Only 24bppRgb can be used");
source = image;
Width = source.Width; Height = source.Height;
PixelCount = Width * Height;
}
private void Lock()
{
if (!locked)
{
Rectangle rect = new Rectangle(0, 0, Width, Height);
bitmapData = source.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
// create byte array to copy pixel values
pixels = new byte[PixelCount * 3];
Iptr = bitmapData.Scan0;
// Copy data from pointer to array
Marshal.Copy(Iptr, pixels, 0, pixels.Length);
locked = true;
}
}
private void Unlock()
{
if (locked)
{
Marshal.Copy(pixels, 0, Iptr, pixels.Length);
source.UnlockBits(bitmapData);
locked = false;
}
}
public Color GetPixel(int x, int y)
{
if (!locked) Lock();
// Get start index of the pixel
int i = (y * Width + x) * 3;
if (i+2 > pixels.Length || i <0) throw new IndexOutOfRangeException();
byte b = pixels[i];
byte g = pixels[i + 1];
byte r = pixels[i + 2];
return Color.FromArgb(r, g, b);
}
public void SetPixel(int x, int y, Color color)
{
if (!locked) Lock();
int i = ((y * Width + x) * 3);
if (i + 2 < pixels.Length && i >= 0)
{
pixels[i] = color.B;
pixels[i + 1] = color.G;
pixels[i + 2] = color.R;
}
}
public void SetPixel(double x, double y, Color color)
{
SetPixel((int)Round(x), (int)Round(y), color);
}
public static implicit operator Bitmap(TImage img)
{
img.Unlock();
return img.source;
}
}

Image color invert on button click C#

I'm using WinForms. I got a picturebox which contains an image. On button click I want to invert the colors of this image back and forth. I tried to make the images invert faster by a button click with the code below. The problem I'm having is that I get an error
Error: Where the code says: Parallel.ForEach(rect.SubRectangles <- I get an error: 'Rectangle' does not contain a definition fo subRectangles' and no extension method 'SubRectangles' accepting a first argument of type 'Rectangel' could be found
2nd error: Under the IEnumerable<Rectangle>SubRectangles <--- (Extension)IEnumerable<Rectangle>ImageUtility.SubRectangle(this Rectanger,... Extension methods must be defined in a top level static class; ImageUtility is a nested class.
Another issue I'm having is calling this code into the button click event so it could work. I'm still learning how to program.
public static class ImageUtility
{
public static Bitmap Process(Bitmap bmp)
{
Bitmap retBmp = new Bitmap(bmp);
var depth = Bitmap.GetPixelFormatSize(bmp.PixelFormat) / 8;
if (depth < 3) throw new ArgumentException("Image must be at least 24 bpp.");
var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
var data = bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
var buffer = new byte[data.Width * data.Height * depth];
//copy pixels to buffer
Marshal.Copy(data.Scan0, buffer, 0, buffer.Length);
bmp.UnlockBits(data);
//Process Image
Parallel.ForEach(rect.SubRectangles(2, 4), r => InvertColor(buffer, r, data.Width, depth));
//Copy the buffer back to image
data = retBmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);
Marshal.Copy(buffer, 0, data.Scan0, buffer.Length);
retBmp.UnlockBits(data);
return retBmp;
}
static void InvertColor(byte[] buffer, Rectangle r, int orgWidth, int depth)
{
for (int i = r.X; i < r.X + r.Width; i++)
{
for (int j = r.Y; j < r.Y + r.Height; j++)
{
var offset = ((j * orgWidth) + i) * depth;
buffer[offset + 0] = (byte)(255 - buffer[offset + 0]);
buffer[offset + 1] = (byte)(255 - buffer[offset + 1]);
buffer[offset + 2] = (byte)(255 - buffer[offset + 2]);
}
}
}
public static IEnumerable<Rectangle> SubRectangles(this Rectangle r, int dx, int dy)
{
int incX = (r.Width - r.X) / dx;
int incY = (r.Height - r.Y) / dy;
for (int y = r.Y; y < r.Height; y += incY)
{
for (int x = r.X; x < r.Width; x += incX)
{
yield return new Rectangle(x, y, incX, incY);
}
}
}
}
private void button_Color_Invert_Click(object sender, EventArgs e)
{
//TO DO:
}
Well, it compiles for me. Is your class ImageUtility nested in another class? It shouldn't be, because extension methods must be placed in a top level static class. That's what your second error message is saying. The method SubRectangles is an extension method, because of the this keyword in the parameter list.
class ImageUtility should be placed in its own file.
public static class A // Top level and static
{
class B // Nested
{
}
}
See:
- Static Classes and Static Class Members (C# Programming Guide)
- Extension Methods (C# Programming Guide)

From C# serverside, Is there anyway to generate a treemap and save as an image?

I have been using this javascript library to create treemap on webpages and it works great. The issue now is that I need to include this in a powerpoint presentation that I am generating on the server side (I am generating the powerpoint using aspose.slides for .net)
The easiest thing I thought of was to try to somehow build a treemap on the server and save as an image (as adding an image into the powerpoint presentation is quite simple) but after googling, I don't see any solution that from C# serverside can generate a treemap as an image.
Does something like this exist where I can create a treemap as an image from a server side C# app.
Given that algorithms are known, it's not hard to just draw a bitmap with a treemap. At the moment I don't have enough time to write code myself, but I have enough time to (almost) mindlessly port some existing code to C# :) Let's take this javascript implementation. It uses algorithm described in this paper. I found some problems in that implementation, which are fixed in C# version. Javascript version works with pure arrays (and arrays of arrays of arrays) of integers. We define some class instead:
public class TreemapItem {
private TreemapItem() {
FillBrush = Brushes.White;
BorderBrush = Brushes.Black;
TextBrush = Brushes.Black;
}
public TreemapItem(string label, int area, Brush fillBrush) : this() {
Label = label;
Area = area;
FillBrush = fillBrush;
Children = null;
}
public TreemapItem(params TreemapItem[] children) : this() {
// in this implementation if there are children - all other properies are ignored
// but this can be changed in future
Children = children;
}
// Label to write on rectangle
public string Label { get; set; }
// color to fill rectangle with
public Brush FillBrush { get; set; }
// color to fill rectangle border with
public Brush BorderBrush { get; set; }
// color of label
public Brush TextBrush { get; set; }
// area
public int Area { get; set; }
// children
public TreemapItem[] Children { get; set; }
}
Then starting to port. First Container class:
class Container {
public Container(int x, int y, int width, int height) {
X = x;
Y = y;
Width = width;
Height = height;
}
public int X { get; }
public int Y { get; }
public int Width { get; }
public int Height { get; }
public int ShortestEdge => Math.Min(Width, Height);
public IDictionary<TreemapItem, Rectangle> GetCoordinates(TreemapItem[] row) {
// getCoordinates - for a row of boxes which we've placed
// return an array of their cartesian coordinates
var coordinates = new Dictionary<TreemapItem, Rectangle>();
var subx = this.X;
var suby = this.Y;
var areaWidth = row.Select(c => c.Area).Sum()/(float) Height;
var areaHeight = row.Select(c => c.Area).Sum()/(float) Width;
if (Width >= Height) {
for (int i = 0; i < row.Length; i++) {
var rect = new Rectangle(subx, suby, (int) (areaWidth), (int) (row[i].Area/areaWidth));
coordinates.Add(row[i], rect);
suby += (int) (row[i].Area/areaWidth);
}
}
else {
for (int i = 0; i < row.Length; i++) {
var rect = new Rectangle(subx, suby, (int) (row[i].Area/areaHeight), (int) (areaHeight));
coordinates.Add(row[i], rect);
subx += (int) (row[i].Area/areaHeight);
}
}
return coordinates;
}
public Container CutArea(int area) {
// cutArea - once we've placed some boxes into an row we then need to identify the remaining area,
// this function takes the area of the boxes we've placed and calculates the location and
// dimensions of the remaining space and returns a container box defined by the remaining area
if (Width >= Height) {
var areaWidth = area/(float) Height;
var newWidth = Width - areaWidth;
return new Container((int) (X + areaWidth), Y, (int) newWidth, Height);
}
else {
var areaHeight = area/(float) Width;
var newHeight = Height - areaHeight;
return new Container(X, (int) (Y + areaHeight), Width, (int) newHeight);
}
}
}
Then Treemap class which builds actual Bitmap
public class Treemap {
public Bitmap Build(TreemapItem[] items, int width, int height) {
var map = BuildMultidimensional(items, width, height, 0, 0);
var bmp = new Bitmap(width, height);
var g = Graphics.FromImage(bmp);
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
foreach (var kv in map) {
var item = kv.Key;
var rect = kv.Value;
// fill rectangle
g.FillRectangle(item.FillBrush, rect);
// draw border
g.DrawRectangle(new Pen(item.BorderBrush, 1), rect);
if (!String.IsNullOrWhiteSpace(item.Label)) {
// draw text
var format = new StringFormat();
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Center;
var font = new Font("Arial", 16);
g.DrawString(item.Label, font, item.TextBrush, new RectangleF(rect.X, rect.Y, rect.Width, rect.Height), format);
}
}
return bmp;
}
private Dictionary<TreemapItem, Rectangle> BuildMultidimensional(TreemapItem[] items, int width, int height, int x, int y) {
var results = new Dictionary<TreemapItem, Rectangle>();
var mergedData = new TreemapItem[items.Length];
for (int i = 0; i < items.Length; i++) {
// calculate total area of children - current item's area is ignored
mergedData[i] = SumChildren(items[i]);
}
// build a map for this merged items (merged because their area is sum of areas of their children)
var mergedMap = BuildFlat(mergedData, width, height, x, y);
for (int i = 0; i < items.Length; i++) {
var mergedChild = mergedMap[mergedData[i]];
// inspect children of children in the same way
if (items[i].Children != null) {
var headerRect = new Rectangle(mergedChild.X, mergedChild.Y, mergedChild.Width, 20);
results.Add(mergedData[i], headerRect);
// reserve 20 pixels of height for header
foreach (var kv in BuildMultidimensional(items[i].Children, mergedChild.Width, mergedChild.Height - 20, mergedChild.X, mergedChild.Y + 20)) {
results.Add(kv.Key, kv.Value);
}
}
else {
results.Add(mergedData[i], mergedChild);
}
}
return results;
}
private Dictionary<TreemapItem, Rectangle> BuildFlat(TreemapItem[] items, int width, int height, int x, int y) {
// normalize all area values for given width and height
Normalize(items, width*height);
var result = new Dictionary<TreemapItem, Rectangle>();
Squarify(items, new TreemapItem[0], new Container(x, y, width, height), result);
return result;
}
private void Normalize(TreemapItem[] data, int area) {
var sum = data.Select(c => c.Area).Sum();
var multi = area/(float) sum;
foreach (var item in data) {
item.Area = (int) (item.Area*multi);
}
}
private void Squarify(TreemapItem[] data, TreemapItem[] currentRow, Container container, Dictionary<TreemapItem, Rectangle> stack) {
if (data.Length == 0) {
foreach (var kv in container.GetCoordinates(currentRow)) {
stack.Add(kv.Key, kv.Value);
}
return;
}
var length = container.ShortestEdge;
var nextPoint = data[0];
if (ImprovesRatio(currentRow, nextPoint, length)) {
currentRow = currentRow.Concat(new[] {nextPoint}).ToArray();
Squarify(data.Skip(1).ToArray(), currentRow, container, stack);
}
else {
var newContainer = container.CutArea(currentRow.Select(c => c.Area).Sum());
foreach (var kv in container.GetCoordinates(currentRow)) {
stack.Add(kv.Key, kv.Value);
}
Squarify(data, new TreemapItem[0], newContainer, stack);
}
}
private bool ImprovesRatio(TreemapItem[] currentRow, TreemapItem nextNode, int length) {
// if adding nextNode
if (currentRow.Length == 0)
return true;
var newRow = currentRow.Concat(new[] {nextNode}).ToArray();
var currentRatio = CalculateRatio(currentRow, length);
var newRatio = CalculateRatio(newRow, length);
return currentRatio >= newRatio;
}
private int CalculateRatio(TreemapItem[] row, int length) {
var min = row.Select(c => c.Area).Min();
var max = row.Select(c => c.Area).Max();
var sum = row.Select(c => c.Area).Sum();
return (int) Math.Max(Math.Pow(length, 2)*max/Math.Pow(sum, 2), Math.Pow(sum, 2)/(Math.Pow(length, 2)*min));
}
private TreemapItem SumChildren(TreemapItem item) {
int total = 0;
if (item.Children?.Length > 0) {
total += item.Children.Sum(c => c.Area);
foreach (var child in item.Children) {
total += SumChildren(child).Area;
}
}
else {
total = item.Area;
}
return new TreemapItem(item.Label, total, item.FillBrush);
}
}
Now let's try to use and see how it goes:
var map = new[] {
new TreemapItem("ItemA", 0, Brushes.DarkGray) {
Children = new[] {
new TreemapItem("ItemA-1", 200, Brushes.White),
new TreemapItem("ItemA-2", 500, Brushes.BurlyWood),
new TreemapItem("ItemA-3", 600, Brushes.Purple),
}
},
new TreemapItem("ItemB", 1000, Brushes.Yellow) {
},
new TreemapItem("ItemC", 0, Brushes.Red) {
Children = new[] {
new TreemapItem("ItemC-1", 200, Brushes.White),
new TreemapItem("ItemC-2", 500, Brushes.BurlyWood),
new TreemapItem("ItemC-3", 600, Brushes.Purple),
}
},
new TreemapItem("ItemD", 2400, Brushes.Blue) {
},
new TreemapItem("ItemE", 0, Brushes.Cyan) {
Children = new[] {
new TreemapItem("ItemE-1", 200, Brushes.White),
new TreemapItem("ItemE-2", 500, Brushes.BurlyWood),
new TreemapItem("ItemE-3", 600, Brushes.Purple),
}
},
};
using (var bmp = new Treemap().Build(map, 1024, 1024)) {
bmp.Save("output.bmp", ImageFormat.Bmp);
}
Output:
This can be extended in multiple ways, and code quality can certainly be improved significantly. But if you would go this way, it can at least give you a good start. Benefit is that it's fast and no external dependencies involved.
If you would want to use it and find some issues or it does not match some of your requirements - feel free to ask and I will improve it when will have more time.
Using the GDI+ api may be your only choice, with good support cross platform. However, there are several potential issues you need to be aware of when doing anything with GDI+ on the server side. It's worth reading this as it explains the current state of drawing Graphics in DotNet and has a point on Server-side processing:
https://github.com/imazen/Graphics-vNext
Having said that; there's this article that deals with what you're asking for:
OutOfMemory Exception when recursively drawing rectangles in GDI+ (It's specifically talking about generating a TreeMap with GDI+ and if you read the comments and answer you'll avoid a lot of the pitfalls)
Once you've generated your image, it's a trivial process to save it to disk somewhere and then, hopefully, embed it within your presentation; you have options to write to streams as well, so it may be possible to directly embed it in the powerpoint file without first saving it to disk.
You can use WPF rendering: http://lordzoltan.blogspot.co.uk/2010/09/using-wpf-to-render-bitmaps.html but it's not without its drawbacks.
(That's a link to my own old blog - but if you search for 'using wpf to generate images' you'll get lots of other examples - many of which are better than mine!)
Generating a tree in WPF is going to be, well, challenging, though - although it can be done, since the WPF drawing primitives are hierarchical in nature.
It might not be suitable, bou could also consider GraphViz - https://github.com/JamieDixon/GraphViz-C-Sharp-Wrapper however I don't know how much luck you'll have executing the command line in a web server.
There are - I expect - bound to be paid-for libraries to do this, as well, as it's a common need.
The Eindhoven University of Technology has published a paper on the algorithm of squarified treemaps. Pascal Laurin has turned this into C#. There is also a Code Project article that has a section about treemaps.
Of course there are also commercial solutions like the one from .NET Charting, Infragistics or Telerik. The downside of those is probably that they are designed as Controls which need to be painted, so you might need some sort of UI thread.
There is also a question here on Stack Overflow that already asked for treemap implementations in C#. Just in case you don't remember.
Since you are already generating the JS and the HTML version of everything, one thing you might want to check out is :
http://www.nrecosite.com/html_to_image_generator_net.aspx
I use this to generate high res-graphic reports straight from my generated pages. It used WKHTML to render it and you can pass a ton of parameters to it to really fine tune it. Its free to most things and it works great. Multi-threading is kind of a pain in the butt with it but I haven't run into to many issues. If you use the NRECO PDf library you can even do batches of stuff also.
With this all you would have to do is render the page like you already are, pipe it through the library and insert into your PPT and all should be good.
Since all you need to do is to extract a screenshot of the web page, it would be more convenient to capture the web page as an Image.
This free library is capable of extracting screenshot from your web page, and it supports Javascript / CSS.
I'm basing the following solution in this project about treemaps in WPF.
Using the data in your link, you can define your model (only with necesary data) like this:
class Data
{
[JsonProperty("$area")]
public float Area { get; set; }
[JsonProperty("$color")]
public Color Color { get; set; }
}
class Item
{
public string Name { get; set; }
public Data Data { get; set; }
public IEnumerable<Item> Children { get; set; }
internal TreeMapData TMData { get; set; }
internal int GetDepth()
{
return Children.Select(c => c.GetDepth()).DefaultIfEmpty().Max() + 1;
}
}
Adding an extra property TreeMapData with some values used in the solution:
class TreeMapData
{
public float Area { get; set; }
public SizeF Size { get; set; }
public PointF Location { get; set; }
}
Now, defining a TreeMap class with the following public members:
class TreeMap
{
public IEnumerable<Item> Items { get; private set; }
public TreeMap(params Item[] items) :
this(items.AsEnumerable()) { }
public TreeMap(IEnumerable<Item> items)
{
Items = items.OrderByDescending(t => t.Data.Area).ThenByDescending(t => t.Children.Count());
}
public Bitmap Draw(int width, int height)
{
var bmp = new Bitmap(width + 1, height + 1);
using (var g = Graphics.FromImage(bmp))
{
DrawIn(g, 0, 0, width, height);
g.Flush();
}
return bmp;
}
//Private members
}
So, you can use it like this:
var treeMap = new TreeMap(items);
var bmp = treeMap.Draw(1366, 768);
And the private/helper members:
private RectangleF emptyArea;
private void DrawIn(Graphics g, float x, float y, float width, float height)
{
Measure(width, height);
foreach (var item in Items)
{
var sFormat = new StringFormat
{
Alignment = StringAlignment.Center,
LineAlignment = StringAlignment.Center
};
if (item.Children.Count() > 0)
{
g.FillRectangle(Brushes.DimGray, x + item.TMData.Location.X, y + item.TMData.Location.Y, item.TMData.Size.Width, 15);
g.DrawString(item.Name, SystemFonts.DefaultFont, Brushes.LightGray, new RectangleF(x + item.TMData.Location.X, y + item.TMData.Location.Y, item.TMData.Size.Width, 15), sFormat);
var treeMap = new TreeMap(item.Children);
treeMap.DrawIn(g, x + item.TMData.Location.X, y + item.TMData.Location.Y + 15, item.TMData.Size.Width, item.TMData.Size.Height - 15);
}
else
{
g.FillRectangle(new SolidBrush(item.Data.Color), x + item.TMData.Location.X, y + item.TMData.Location.Y, item.TMData.Size.Width, item.TMData.Size.Height);
g.DrawString(item.Name, SystemFonts.DefaultFont, Brushes.Black, new RectangleF(x + item.TMData.Location.X, y + item.TMData.Location.Y, item.TMData.Size.Width, item.TMData.Size.Height), sFormat);
}
var pen = new Pen(Color.Black, item.GetDepth() * 1.5f);
g.DrawRectangle(pen, x + item.TMData.Location.X, y + item.TMData.Location.Y, item.TMData.Size.Width, item.TMData.Size.Height);
}
g.Flush();
}
private void Measure(float width, float height)
{
emptyArea = new RectangleF(0, 0, width, height);
var area = width * height;
var sum = Items.Sum(t => t.Data.Area + 1);
foreach (var item in Items)
{
item.TMData = new TreeMapData();
item.TMData.Area = area * (item.Data.Area + 1) / sum;
}
Squarify(Items, new List<Item>(), ShortestSide());
foreach (var child in Items)
if (!IsValidSize(child.TMData.Size))
child.TMData.Size = new Size(0, 0);
}
private void Squarify(IEnumerable<Item> items, IEnumerable<Item> row, float sideLength)
{
if (items.Count() == 0)
{
ComputeTreeMaps(row);
return;
}
var item = items.First();
List<Item> row2 = new List<Item>(row);
row2.Add(item);
List<Item> items2 = new List<Item>(items);
items2.RemoveAt(0);
float worst1 = Worst(row, sideLength);
float worst2 = Worst(row2, sideLength);
if (row.Count() == 0 || worst1 > worst2)
Squarify(items2, row2, sideLength);
else
{
ComputeTreeMaps(row);
Squarify(items, new List<Item>(), ShortestSide());
}
}
private void ComputeTreeMaps(IEnumerable<Item> items)
{
var orientation = this.GetOrientation();
float areaSum = 0;
foreach (var item in items)
areaSum += item.TMData.Area;
RectangleF currentRow;
if (orientation == RowOrientation.Horizontal)
{
currentRow = new RectangleF(emptyArea.X, emptyArea.Y, areaSum / emptyArea.Height, emptyArea.Height);
emptyArea = new RectangleF(emptyArea.X + currentRow.Width, emptyArea.Y, Math.Max(0, emptyArea.Width - currentRow.Width), emptyArea.Height);
}
else
{
currentRow = new RectangleF(emptyArea.X, emptyArea.Y, emptyArea.Width, areaSum / emptyArea.Width);
emptyArea = new RectangleF(emptyArea.X, emptyArea.Y + currentRow.Height, emptyArea.Width, Math.Max(0, emptyArea.Height - currentRow.Height));
}
float prevX = currentRow.X;
float prevY = currentRow.Y;
foreach (var item in items)
{
var rect = GetRectangle(orientation, item, prevX, prevY, currentRow.Width, currentRow.Height);
item.TMData.Size = rect.Size;
item.TMData.Location = rect.Location;
ComputeNextPosition(orientation, ref prevX, ref prevY, rect.Width, rect.Height);
}
}
private RectangleF GetRectangle(RowOrientation orientation, Item item, float x, float y, float width, float height)
{
if (orientation == RowOrientation.Horizontal)
return new RectangleF(x, y, width, item.TMData.Area / width);
else
return new RectangleF(x, y, item.TMData.Area / height, height);
}
private void ComputeNextPosition(RowOrientation orientation, ref float xPos, ref float yPos, float width, float height)
{
if (orientation == RowOrientation.Horizontal)
yPos += height;
else
xPos += width;
}
private RowOrientation GetOrientation()
{
return emptyArea.Width > emptyArea.Height ? RowOrientation.Horizontal : RowOrientation.Vertical;
}
private float Worst(IEnumerable<Item> row, float sideLength)
{
if (row.Count() == 0) return 0;
float maxArea = 0;
float minArea = float.MaxValue;
float totalArea = 0;
foreach (var item in row)
{
maxArea = Math.Max(maxArea, item.TMData.Area);
minArea = Math.Min(minArea, item.TMData.Area);
totalArea += item.TMData.Area;
}
if (minArea == float.MaxValue) minArea = 0;
float val1 = (sideLength * sideLength * maxArea) / (totalArea * totalArea);
float val2 = (totalArea * totalArea) / (sideLength * sideLength * minArea);
return Math.Max(val1, val2);
}
private float ShortestSide()
{
return Math.Min(emptyArea.Width, emptyArea.Height);
}
private bool IsValidSize(SizeF size)
{
return (!size.IsEmpty && size.Width > 0 && size.Width != float.NaN && size.Height > 0 && size.Height != float.NaN);
}
private enum RowOrientation
{
Horizontal,
Vertical
}
Finally, to parse and draw the json in the example I'm doing this:
var json = File.ReadAllText(#"treemap.json");
var items = JsonConvert.DeserializeObject<Item>(json);
var treeMap = new TreeMap(items);
var bmp = treeMap.Draw(1366, 768);
bmp.Save("treemap.png", ImageFormat.Png);
And the resulting image:
Actually I don't know if the following can help you or not since you aren't using vsto, AND AS SAID IN THE COMMENTS PROBABLY IS A BAD IDEA.
Starting in Office 2016, treemaps are incorporated as charts. You can read this to see how create treemaps from datasets in Excel.
So, you can generate the chart in Excel and pass it to PowerPoint:
//Start an hidden excel application
var appExcel = new Excel.Application { Visible = false };
var workbook = appExcel.Workbooks.Add();
var sheet = workbook.ActiveSheet;
//Generate some random data
Random r = new Random();
for (int i = 1; i <= 10; i++)
{
sheet.Cells[i, 1].Value2 = ((char)('A' + i - 1)).ToString();
sheet.Cells[i, 2].Value2 = r.Next(1, 20);
}
//Select the data to use in the treemap
var range = sheet.Cells.Range["A1", "B10"];
range.Select();
range.Activate();
//Generate the chart
var shape = sheet.Shapes.AddChart2(-1, (Office.XlChartType)117, 200, 25, 300, 300, null);
shape.Chart.ChartTitle.Caption = "Generated TreeMap Chart";
//Copy the chart
shape.Copy();
appExcel.Quit();
//Start a Powerpoint application
var appPpoint = new Point.Application { Visible = Office.MsoTriState.msoTrue };
var presentation = appPpoint.Presentations.Add();
//Add a blank slide
var master = presentation.SlideMaster;
var slide = presentation.Slides.AddSlide(1, master.CustomLayouts[7]);
//Paste the treemap
slide.Shapes.Paste();
Treemap chart in the slide:
Probably you can generate the treemap using the first part (Excel part) and paste the chart using the tool you said, or save the Powerpoint file with the chart generated in VSTO and open it with the tool.
The benefits are that these objects are real charts not just images, so you can change or add colors, styles, effects easily.

How to convert PictureBox image which is created in real-time into bytes?

I have a .net PictureBox on my screen which creates an image in real-time from a signature pad input device.
I am trying to get the bytes from the image to save but because the PictureBox is always open, I am unable to get the .Image property as it is always NULL.
Is there a way to somehow close the PictureBox so I can take the image from it?
This is where I attempt to get the bytes but the .Image is NULL due to the creation in real-time:
private void btnConfirm_Click(object sender, EventArgs e)
{
byte[] imgData = null;
// storage for the img bytes
picSignature.Update();
imgData = ImgToByteArray(picSignature.Image, ImageFormat.Jpeg);
SerialPortListener.MainForm._imagevalues = imgData;
this.Close();
}
This is the code which I believe writes the signature:
private void SignatureDataHandler(Int32 xAxis, Int32 yAxis, Int32 pressure, Int32 timeStamp)
{
long x;
long y;
Pen myPen = new Pen(Color.Black, 1);
x = (picSignature.Width * (xAxis - g_xMin)) / (g_xMax - g_xMin);
y = (picSignature.Height * (yAxis - g_yMin)) / (g_yMax - g_yMin);
if ((x > picSignature.Width) || (x < 0))
{
MessageBox.Show("problem");
}
if (0 != pressure)
{
if (g_fFirstTouch)
{
g_PicGraphics.DrawLine(myPen, x, y, x, y);
g_fFirstTouch = false;
}
else
{
g_PicGraphics.DrawLine(myPen, g_lastX, g_lastY, x, y);
}
}
else
{
g_fFirstTouch = true;
}
g_lastX = x;
g_lastY = y;
}

How can I copy byte[] into byte[,,]?

This question is related to: How to convert Bitmap to byte[,,] faster?
I have byte[] which has:
[r0, g0, b0, r1, g1, b1 ... ]
(r0 is the r-value of zeroth pixel and so on)
How can I copy this quickly into byte[,,]?
Or maybe I can get byte[,,] ditectly from BitmapData?
Based on Martinho's answer but perhaps a bit faster(don't have time for benchmarking now):
struct BitmapDataAccessor
{
private readonly byte[] data;
private readonly int[] rowStarts;
public readonly int Height;
public readonly int Width;
public BitmapDataAccessor(byte[] data, int width, int height)
{
this.data = data;
this.Height = height;
this.Width = width;
rowStarts = new int[height];
for(int y=0;y<height;y++)
rowStarts[y]=y*width;
}
public byte this[int x, int y, int color] // Maybe use an enum with Red = 0, Green = 1, and Blue = 2 members?
{
get { return data[(rowStarts[y] + x) *3 + color]; }
set { data[(rowStarts[y] + x) *3 + color] = value; }
}
public byte[] Data
{
get { return data; }
}
}
Ok, let's say you've got your data in a one-dimensional byte array. Do you really need to push it over into a three-dimensional array? If all you want is an easier way to access the pixel data, why don't you simply write such a simple interface to that array? Something along these lines:
class BitmapDataAccessor
{
private readonly byte[] data;
private readonly int rows;
private readonly int columns;
public BitmapDataAccessor(byte[] data, int rows, int columns)
{
this.data = data;
this.rows = rows;
this.columns = columns;
}
public byte this[int row, int column, int color] // Maybe use an enum with Red = 0, Green = 1, and Blue = 2 members?
{
get { return data[(row * columns + column) * 3 + color]; }
set { data[(row * columns + column) * 3 + color] = value; }
}
public byte[] Data
{
get { return data; }
}
}
How about using something like this for ease of accessing the discrete bytes:
class ByteIndexer
{
private readonly byte[] _bits;
private readonly int _width;
public ByteIndexer(byte[] bits, int width)
{
_bits = bits;
_width = width;
}
public byte this[int x, int y, int c]
{ get { return _bits[(((_width * y) + x) * 3) + c]; } }
}
You could even make it easier, overload this[] with:
public Color this[int x, int y]
{ get { return Color.FromArgb(this[x,y,0], this[x,y,1], this[x,y,2]); }
You could also consider using the built-in Bitmap in System.Drawing. Here's an example with a 4x3 image.
var image = new byte[] {255,255,255,0,0,0,255,255,255,0,0,0,
255,255,255,0,0,0,255,127,255,0,0,0,
0,0,0,255,255,255,0,0,0,255,255,255};
Bitmap bmp = new Bitmap(4, 3, PixelFormat.Format24bppRgb);
BitmapData bmpData = bmp.LockBits(
new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
Marshal.Copy(image, 0, bmpData.Scan0, image.Length);
bmp.UnlockBits(bmpData);
var testPixel = bmp.GetPixel(2, 1);
testPixel will be a System.Drawing.Color set to {Color [A=255, R=255, G=127, B=255]}

Categories