How to prevent my Image from scaling down? - itext

I am using iText 7.2.1.
I create two images in the following code. They are two rectangles, created from PdfFormXObject. The first is 100 x 100, and the second is 1000 x 100. They have the same stroke width. I have SetAutoScale(false) for both images.
using iText.Kernel.Colors;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Layout;
using iText.Kernel.Pdf.Xobject;
namespace iTextTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var writer = new PdfWriter("test.pdf");
var pdfdoc = new PdfDocument(writer);
var doc = new Document(pdfdoc);
// 100 x 100 rectangle
var rect1 = new iText.Kernel.Geom.Rectangle(0, 0, 100, 100);
var xobj1 = new PdfFormXObject(rect1);
var canvas1 = new PdfCanvas(xobj1, pdfdoc);
canvas1.SetStrokeColor(ColorConstants.RED);
canvas1.SetLineWidth(5);
canvas1.Rectangle(rect1);
canvas1.Stroke();
var img1 = new iText.Layout.Element.Image(xobj1).SetAutoScale(false);
doc.Add(img1);
// 1000 x 100 rectangle
var rect2 = new iText.Kernel.Geom.Rectangle(0, 0, 1000, 100);
var xobj2 = new PdfFormXObject(rect2);
var canvas2 = new PdfCanvas(xobj2, pdfdoc);
canvas2.SetStrokeColor(ColorConstants.RED);
canvas2.SetLineWidth(5);
canvas2.Rectangle(rect2);
canvas2.Stroke();
var img2 = new iText.Layout.Element.Image(xobj2).SetAutoScale(false);
doc.Add(img2);
doc.Close();
pdfdoc.Close();
writer.Close();
MessageBox.Show("OK");
}
}
}
When I add them into the document, apparently, the first image is of the original size, but the second image is scaled down.
I want the images to not scale at all even there isn't enough space. How to do this?

Related

How to possible Xamarin Forms Vertical Bar Charts?

In my xamarin forms application, I am using the Oxyplot bar charts. Here is the code, This is work for me in the condition for horizontal bars, How it is possible for creating for vertical graphs? Is there any other plugin for bar charts?
The key is to use a ColumnSeries with ColumnItem objects. This should render as a bar chart that has vertically oriented bars. If you create a new ContentPage and paste the code below into it you can see it in action. I attached an image below the code sample detailing how it looks on iOS.
public partial class DemoPage : ContentPage
{
public DemoPage()
{
InitializeComponent();
var model = new PlotModel { Title = "Cake Type Popularity" };
// generate a random percentage distribution between the 5
//cake-types (see axis below)
var rand = new Random();
double[] cakePopularity = new double[5];
for (int i = 0; i < 5; ++i)
{
cakePopularity[i] = rand.NextDouble();
}
var sum = cakePopularity.Sum();
var barSeries = new ColumnSeries
{
ItemsSource = new List<ColumnItem>(new[]
{
new ColumnItem{ Value = (cakePopularity[0] / sum * 100) },
new ColumnItem{ Value = (cakePopularity[1] / sum * 100) },
new ColumnItem{ Value = (cakePopularity[2] / sum * 100) },
new ColumnItem{ Value = (cakePopularity[3] / sum * 100) },
new ColumnItem{ Value = (cakePopularity[4] / sum * 100) }
}),
LabelPlacement = LabelPlacement.Inside,
LabelFormatString = "{0:.00}%"
};
model.Series.Add(barSeries);
model.Axes.Add(new CategoryAxis
{
Position = AxisPosition.Bottom,
Key = "CakeAxis",
ItemsSource = new[]
{
"A",
"B",
"C",
"D",
"E"
}
});
var grid = new Grid();
grid.Children.Add(new PlotView
{
Model = model,
VerticalOptions = LayoutOptions.Center,
HeightRequest = 200,
HorizontalOptions = LayoutOptions.Fill,
});
Content = grid;
}
}
This should render a graph like this:

Take photo in unity c#

I'm trying to build a program that takes your photo and places it with a different background, like a monument or so. So far, I was able to turn the camera on when I start the project with this code
webcamTexture = new WebCamTexture();
rawImage.texture = webcamTexture;
rawImage.material.mainTexture = webcamTexture;
webcamTexture.Play();
Texture2D PhotoTaken = new Texture2D (webcamTexture.width, webcamTexture.height);
PhotoTaken.SetPixels (webcamTexture.GetPixels ());
PhotoTaken.Apply ();
However, I can't take a screenshot or photo because it always ends up all black. I've tried different codes but nothing is working. Can someone please help? Thanks
EDIT
After some tries, this is the code I have:
WebCamTexture webcamTexture;
public RawImage rawImage;
void Start () {
webcamTexture = new WebCamTexture();
rawImage.texture = webcamTexture;
rawImage.material.mainTexture = webcamTexture;
webcamTexture.Play();
RenderTexture texture= new RenderTexture(webcamTexture.width, webcamTexture.height,0);
Graphics.Blit(webcamTexture, texture);
Button btn = yourButton.GetComponent<Button>();
btn.onClick.AddListener(OnClick);
}
public IEnumerator Coroutine(){
yield return new WaitForEndOfFrame ();
}
public void OnClick() {
var width = 767;
var height = 575;
Texture2D texture = new Texture2D(width, height);
texture.ReadPixels(new Rect(0, 0, width, height), 0, 0);
texture.Apply();
// Encode texture into PNG
var bytes = texture.EncodeToPNG();
//Destroy(texture);
File.WriteAllBytes (Application.dataPath + "/../SavedScreen.png", bytes);
}
and with this next code the screenshot is taken, but it takes a photo of the whole thing, and not just a bit of the screen.
void Start()
{
// Set the playback framerate!
// (real time doesn't influence time anymore)
Time.captureFramerate = frameRate;
// Find a folder that doesn't exist yet by appending numbers!
realFolder = folder;
int count = 1;
while (System.IO.Directory.Exists(realFolder))
{
realFolder = folder + count;
count++;
}
// Create the folder
System.IO.Directory.CreateDirectory(realFolder);
}
void Update()
{
// name is "realFolder/shot 0005.png"
var name = string.Format("{0}/shot {1:D04}.png", realFolder, Time.frameCount);
// Capture the screenshot
Application.CaptureScreenshot(name, sizeMultiplier);
}
}
You can take a screenshot like this in Unity
Application.CaptureScreenshot("Screenshot.png");
Reference
EDIT 1
To take a screenshot on a specific part of the screen use the following script:
var width = 400;
var height = 300;
var startX = 200;
var startY = 100;
var tex = new Texture2D (width, height, TextureFormat.RGB24, false);
tex.ReadPixels (Rect(startX, startY, width, height), 0, 0);
tex.Apply ();
// Encode texture into PNG
var bytes = tex.EncodeToPNG();
Destroy(tex);
File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes);
Reference

Image in mode mosaic in PdfPCell

I am currently using itextPdf library to generate PDF file.
For to set an image I used this solution of itextpdf.com
Now I want to set a small size image as a background in PdfPCell in mode mosaic : if cell have 3 x ImageSize, in PDF I will have my image repeated 3 times in cell
How I can do it ?
this is my example
public class ImageBackgroundEvent implements PdfPCellEvent {
protected Image image;
protected boolean mosaic;
protected boolean full;
public ImageBackgroundEvent(Image image, boolean mosaic, boolean full) {
this.image = image;
this.mosaic = mosaic;
this.full = full;
}
public void cellLayout(PdfPCell cell, Rectangle position,
PdfContentByte[] canvases) {
try {
PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS];
if(full){
cell.setImage(image);
}
else if(mosaic){
float imgWidth = image.getWidth();
float imgHeight = image.getHeight();
float cellWidth = cell.getWidth();
float cellHeight = cell.getHeight();
if(imgHeight < cellHeight && imgWidth < cellWidth){
PdfPatternPainter pattern = cb.createPattern(imgWidth, imgHeight);
pattern.addImage(image);
pattern.setPatternMatrix(-0.5f, 0f, 0f, 0.5f, 0f, 0f);
cb.setPatternFill(pattern);
//cb.ellipse(180, 408, 450, 534);
cb.fillStroke();
} else{
image.scaleAbsolute(position);
image.setAbsolutePosition(position.getLeft(), position.getBottom());
cb.addImage(image);
}
} else{
image.scaleAbsolute(position);
image.setAbsolutePosition(position.getLeft(), position.getBottom());
cb.addImage(image);
}
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
}
}
Please take a look at the TiledBackgroundColor example. It takes an image of a light bulb and uses it to define a pattern color:
PdfContentByte canvas = writer.getDirectContent();
Image image = Image.getInstance(IMG);
PdfPatternPainter img_pattern = canvas.createPattern(
image.getScaledWidth(), image.getScaledHeight());
image.setAbsolutePosition(0, 0);
img_pattern.addImage(image);
BaseColor color = new PatternColor(img_pattern);
Now you can use that color for the background of your cell:
PdfPCell cell = new PdfPCell();
cell.setFixedHeight(60);
cell.setBackgroundColor(color);
table.addCell(cell);
The result looks like this: tiled_patterncolor.pdf
Or you could add the image in a cell event as shown in the TiledBackground example. This example was written in answer to the question iTextSharp. Why cell background image is rotated 90 degrees clockwise?
I've written a variation on this example: TiledBackgroundColor2
The event looks like this:
class TiledImageBackground implements PdfPCellEvent {
protected Image image;
public TiledImageBackground(Image image) {
this.image = image;
}
public void cellLayout(PdfPCell cell, Rectangle position,
PdfContentByte[] canvases) {
try {
PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS];
image.scaleToFit(10000000, position.getHeight());
float x = position.getLeft();
float y = position.getBottom();
while (x + image.getScaledWidth() < position.getRight()) {
image.setAbsolutePosition(x, y);
cb.addImage(image);
x += image.getScaledWidth();
}
} catch (DocumentException e) {
throw new ExceptionConverter(e);
}
}
}
As you see, I don't care about the actual dimensions of the image. I scale the image in such a way that it fits the height of the cell. I don't use a pattern color either. I just add the image as many time as it fits the width of the cell.
This is how I declare the event to the cell:
PdfPCell cell = new PdfPCell();
Image image = Image.getInstance(IMG);
cell.setCellEvent(new TiledImageBackground(image));
The result looks like this:
Many variations are possible depending on your exact requirement.

Kinect-Matlab: Get joint angle information

I am a beginner at kinect and I want to use it with matlab. I need joint angle information out of the skeleton data. What is the easiest way to do this?
Thanks.
I am not good with Mat lab, but try to use c# with Visual Studio. Use the SkeletonBasics-WPF in the Microsoft SDK´s as a template to add this code:
public class Angles
{
public double AngleBetweenTwoVectors(Vector3D vectorA, Vector3D vectorB)
{
double dotProduct;
vectorA.Normalize();
vectorB.Normalize();
dotProduct = Vector3D.DotProduct(vectorA, vectorB);
return (double)Math.Acos(dotProduct)/Math.PI*180;
}
public byte[] GetVector(Skeleton skeleton)
{
Vector3D ShoulderCenter = new Vector3D(skeleton.Joints[JointType.ShoulderCenter].Position.X, skeleton.Joints[JointType.ShoulderCenter].Position.Y, skeleton.Joints[JointType.ShoulderCenter].Position.Z);
Vector3D RightShoulder = new Vector3D(skeleton.Joints[JointType.ShoulderRight].Position.X, skeleton.Joints[JointType.ShoulderRight].Position.Y, skeleton.Joints[JointType.ShoulderRight].Position.Z);
Vector3D LeftShoulder = new Vector3D(skeleton.Joints[JointType.ShoulderLeft].Position.X, skeleton.Joints[JointType.ShoulderLeft].Position.Y, skeleton.Joints[JointType.ShoulderLeft].Position.Z);
Vector3D RightElbow = new Vector3D(skeleton.Joints[JointType.ElbowRight].Position.X, skeleton.Joints[JointType.ElbowRight].Position.Y, skeleton.Joints[JointType.ElbowRight].Position.Z);
Vector3D LeftElbow = new Vector3D(skeleton.Joints[JointType.ElbowLeft].Position.X, skeleton.Joints[JointType.ElbowLeft].Position.Y, skeleton.Joints[JointType.ElbowLeft].Position.Z);
Vector3D RightWrist = new Vector3D(skeleton.Joints[JointType.WristRight].Position.X, skeleton.Joints[JointType.WristRight].Position.Y, skeleton.Joints[JointType.WristRight].Position.Z);
Vector3D LeftWrist = new Vector3D(skeleton.Joints[JointType.WristLeft].Position.X, skeleton.Joints[JointType.WristLeft].Position.Y, skeleton.Joints[JointType.WristLeft].Position.Z);
Vector3D UpVector = new Vector3D(0.0, 1.0, 0.0);
double AngleRightElbow = AngleBetweenTwoVectors(RightElbow - RightShoulder, RightElbow - RightWrist);
double AngleRightShoulder = AngleBetweenTwoVectors(UpVector, RightShoulder - RightElbow);
double AngleLeftElbow = AngleBetweenTwoVectors(LeftElbow - LeftShoulder, LeftElbow - LeftWrist);
double AngleLeftShoulder = AngleBetweenTwoVectors(UpVector, LeftShoulder - LeftElbow);
byte[] Angles = {Convert.ToByte(AngleRightElbow), Convert.ToByte(AngleRightShoulder),Convert.ToByte(AngleLeftElbow),Convert.ToByte(AngleLeftShoulder)};
return Angles;
}
}
Insert this at the top. Call the GetVector() method here:
private void SensorSkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
Skeleton[] skeletons = new Skeleton[0];
using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
{
if (skeletonFrame != null)
{
skeletons = new Skeleton[skeletonFrame.SkeletonArrayLength];
skeletonFrame.CopySkeletonDataTo(skeletons);
}
}
using (DrawingContext dc = this.drawingGroup.Open())
{
// Draw a transparent background to set the render size
dc.DrawRectangle(Brushes.Black, null, new Rect(0.0, 0.0, RenderWidth, RenderHeight));
if (skeletons.Length != 0)
{
foreach (Skeleton skel in skeletons)
{
RenderClippedEdges(skel, dc);
if (skel.TrackingState == SkeletonTrackingState.Tracked)
{
this.DrawBonesAndJoints(skel, dc);
Angles MyAngles = new Angles();
byte[] ReadyAngles = MyAngles.GetVector(skel);
RightElbow.Text = ReadyAngles[0].ToString();
RightShoulder.Text = ReadyAngles[1].ToString();
LeftElbow.Text = ReadyAngles[2].ToString();
LeftShoulder.Text = ReadyAngles[3].ToString();
byte[] SequenceStart = {255};
if (ArduinoPort.IsOpen)
{
ArduinoPort.Write(SequenceStart,0,1);
ArduinoPort.Write(ReadyAngles, 0, 4);
}
}
else if (skel.TrackingState == SkeletonTrackingState.PositionOnly)
{
dc.DrawEllipse(
this.centerPointBrush,
null,
this.SkeletonPointToScreen(skel.Position),
BodyCenterThickness,
BodyCenterThickness);
}
}
}
// prevent drawing outside of our render area
this.drawingGroup.ClipGeometry = new RectangleGeometry(new Rect(0.0, 0.0, RenderWidth, RenderHeight));
}
}
As you can see I added 4 textboxes as I am calculating 4 Angles (RS, LF, RE, LE). These Angles are being passed to the textbox in my .xaml file. I hope this works for you.
You would need the Image Acquisition Toolbox, which includes support for Kinect including skeleton data.

ILNumerics 3D Contour plots legend is not displayed why?

I use to create a surface contour of the 3D contour plots.
I have now been drawing contour lines in my 3D figure, this also works wonderfully, but the legend is not displayed why?
code:
private void button1_Click(object sender, EventArgs e)
{
ILArray<float> data = ILSpecialData.sincf(50, 50);
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += bgwCreateProcess_DoWork;
bgw.RunWorkerAsync(data);
}
private void bgwCreateProcess_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
ILArray<float> data = e.Argument as ILArray<float>;
using (ILScope.Enter())
{
ILScene scene = new ILScene();
ILPlotCube plotCube = new ILPlotCube(twoDMode: false);
plotCube.Rotation = Matrix4.Rotation(new Vector3(1, 0, 0), Math.PI / 2);
ILSurface surface = new ILSurface(data);
List<ContourLevel> conturLevels = new List<ContourLevel>();
conturLevels.Add(new ContourLevel() { Text = "Limit Max", Value = 0.9f, LineWidth = 2 });
conturLevels.Add(new ContourLevel() { Text = "Limit Min", Value = -0.1f, LineWidth = 2 });
conturLevels.Add(new ContourLevel() { Text = "Average", Value = 0.5f, LineWidth = 3 });
ILContourPlot contourPlot = new ILContourPlot(data, conturLevels, create3D: true);
plotCube.Children.Add(contourPlot);
ILLegend legend = new ILLegend();
legend.Location = new PointF(.99f, 0f);
surface.Children.Add(legend);
ILColorbar colorbar = new ILColorbar();
colorbar.Location = new PointF(.99f, 0.4f);
surface.Children.Add(colorbar);
surface.Markable = false;
surface.Fill.Markable = false;
surface.Wireframe.Markable = false;
surface.Wireframe.Visible = true;
surface.UseLighting = false;
plotCube.Add(surface);
scene.Add(plotCube);
ilPanel.Scene = scene;
}
}
This code should be extended to a winform, a ILPanel and a button. Last but the Click event of the button has to be subscribed. Less code is not possible, because otherwise the situation is changed.
Felix, there are several issues in the code. Some of them are related to a bug in ILNumerics which will be fixed in the next version. The following code creates an image like that:
private void button1_Click(object sender, EventArgs e) {
ILArray<float> data = ILSpecialData.sincf(50, 50);
BackgroundWorker bgw = new BackgroundWorker();
bgw.DoWork += bgwCreateProcess_DoWork;
bgw.RunWorkerAsync(data);
}
private void bgwCreateProcess_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
using (ILScope.Enter()) {
ILArray<float> data = e.Argument as ILArray<float>;
ILScene scene = new ILScene();
ILPlotCube plotCube = new ILPlotCube(twoDMode: false);
plotCube.Rotation = Matrix4.Rotation(new Vector3(1, 0, 0), Math.PI / 2);
ILSurface surface = new ILSurface(data);
List<ContourLevel> conturLevels = new List<ContourLevel>();
conturLevels.Add(new ContourLevel() { Text = "Limit Max", Value = 0.9f, LineWidth = 2 });
conturLevels.Add(new ContourLevel() { Text = "Limit Min", Value = -0.1f, LineWidth = 2 });
conturLevels.Add(new ContourLevel() { Text = "Average", Value = 0.5f, LineWidth = 3 });
ILContourPlot contourPlot = new ILContourPlot(data, conturLevels, create3D: true);
plotCube.Add(contourPlot);
ILLegend legend = new ILLegend("one","two","three","four");
legend.Location = new PointF(.99f, 0f);
ILColorbar colorbar = new ILColorbar();
colorbar.Location = new PointF(.99f, 0.4f);
surface.Add(colorbar);
surface.Markable = false;
surface.Fill.Markable = false;
surface.Wireframe.Markable = false;
surface.Wireframe.Visible = true;
surface.UseLighting = false;
plotCube.Add(surface);
surface.Fill.Visible = false;
scene.Add(plotCube);
contourPlot.Add(legend);
legend.Configure(); // only needed in version 3.2.2.0!
scene.Configure();
ilPanel1.Scene = scene;
}
}
Let's step through the code:
As you see, I hided the surface fill color. Otherwise, the labels of the contour plot might get hidden by the surface.
Legends should be added to the plot they are about to describe. I added the legend to the contourplot instead of the surface. However, for some reasons, the legend does not automatically find the contour lines from the contour plot, so...
... I added the legend entries manually in the legend constructor. Here, I just used the strings "one"... "three". You will want to replace that with your own names.
Due to the bug I mentioned, you will have to call legend.Configure() explicitely. This will not be needed after version 3.2.2.0.
You are doing the scene modifications in a background worker thread - which is fine! However, after having finished the configuration, the panel must be signaled to refresh itself. ilPanel.Refresh(), however, requires to be called from the main (GUI-) thread. So I suspect, you could use Control.Invoke() at the end of bgwCreateProcess_DoWork in order to call ilPanel.Refresh(). Otherwise, the changes will not display.