Im using a custom WebView component in android to display an html page with HTML5 canvas.
Due to lack of WebView support for the getDataUrl from canvas function,
im passing the getImageData.data Uint8ClampedArray to webview through web view JavascriptInterface.
It saves the images as a dark blue image. Any ideias?
// html
...canvas id="canvas" width="20px" height="20px"...
// javascript
imgData=context.getImageData(0,0,20,20);
webViewArray = Array.prototype.slice.call(imgData.data);
webviewApp.procData(webViewArraySTRING);
// android
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int[] results = new int[1600];
int[] icnt = 0;
int width = 20;
int height = 20;
int pos = 0, end;
while((end = webViewArraySTRING.indexOf(',', pos)) >= 0) {
results[icnt] = Integer.parseInt(webViewArraySTRING.substring(pos,end));
pos = end + 1;
icnt++;
}
// create image - tried using ARGB_8888, ARGB_4444
System.out.println("results size:" + icnt); // prints out 1599
Bitmap bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.RGB_565);
bitmap.setPixels(results, 0, width, 0, 0, width, height);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
// save image `
FileOutputStream os = new FileOutputStream(file,true);
os.write(boas.toByteArray());
Related
I have an application that generates PDFs using the MigraDoc framework, however I have a requirement to add in a text driven watermark. I have found some examples of this being done using PDF Sharp here, however I just cant seem t be able to figure out how this will integrate with my Migradoc Document() object I am rendering.
I have the following code:
public byte[] render()
{
PdfDocument document = new PdfDocument();
CreateWaterMarks(document);
// *****************************
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
renderer.Document = this.document;
renderer.RenderDocument();
byte[] pdfContents = null;
using (MemoryStream stream = new MemoryStream())
{
renderer.PdfDocument.Save(stream, true);
pdfContents = stream.ToArray();
}
return pdfContents;
}
This method is what is called to render the MigraDoc document and pass it out as a byte array. The second line of code in here calls the following method which is not doing what I am looking for:
void CreateWaterMarks(PdfDocument document)
{
PdfPage page = document.AddPage();
Document doc = this.document;
MigraDoc.Rendering.DocumentRenderer docRenderer = new DocumentRenderer(doc);
docRenderer.PrepareDocument();
XRect A4Rect = new XRect(0, 0, pageActiveWidth, pageActiveHeight);
int pageCount = docRenderer.FormattedDocument.PageCount;
for (int idx = 0; idx < pageCount; idx++)
{
XFont font = new XFont("Verdana", 13, XFontStyle.Bold);
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
XSize size = gfx.MeasureString("Watermark", font);
gfx.TranslateTransform(pageActiveWidth / 2, pageActiveHeight / 2);
gfx.RotateTransform(-Math.Atan(pageActiveHeight / pageActiveWidth) * 180 / Math.PI);
gfx.TranslateTransform(-pageActiveWidth / 2, -pageActiveHeight / 2);
XStringFormat format = new XStringFormat();
format.Alignment = XStringAlignment.Near;
format.LineAlignment = XLineAlignment.Near;
XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));
gfx.DrawString("Watermark", font, brush, new XPoint((pageActiveWidth - size.Width) / 2, (pageActiveHeight - size.Height) / 2), format);
docRenderer.RenderPage(gfx, idx + 1);
}
}
I was hoping that this would magically make these PDFSharp watermarks appear but alas I get nothing!
I have this working using the following code:
public byte[] render()
{
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true);
renderer.Document = this.document;
renderer.RenderDocument();
renderer.PrepareRenderPages();
CreateWatermarks(renderer);
byte[] pdfContents = null;
using (MemoryStream stream = new MemoryStream())
{
renderer.PdfDocument.Save(stream, true);
pdfContents = stream.ToArray();
}
return pdfContents;
}
private void CreateWatermarks(PdfDocumentRenderer renderer)
{
int pages = renderer.DocumentRenderer.FormattedDocument.PageCount;
for (int i = 0; i < pages; ++i)
{
var page = renderer.PdfDocument.Pages[i];
XFont font = new XFont("Verdana", 27, XFontStyle.Bold);
XGraphics gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Prepend);
XSize size = gfx.MeasureString("Watermark", font);
gfx.TranslateTransform(pageActiveWidth / 2, pageActiveHeight / 2);
gfx.RotateTransform(-Math.Atan(pageActiveHeight / pageActiveWidth) * 180 / Math.PI);
gfx.TranslateTransform(-pageActiveWidth / 2, -pageActiveHeight / 2);
XStringFormat format = new XStringFormat();
format.Alignment = XStringAlignment.Near;
format.LineAlignment = XLineAlignment.Near;
XBrush brush = new XSolidBrush(XColor.FromArgb(128, 255, 0, 0));
gfx.DrawString("Watermark", font, brush, new XPoint((pageActiveWidth - size.Width) / 2, (pageActiveHeight - size.Height) / 2), format);
}
}
I have been struggling in taking screenshots with DirectX, the problem is, it's working but seems to be missing some colors (black outline is missing for example), and some stuff that is also rendered by DX doesn't show.
I have uploaded the images (how the image should render and the rendered one) and also the code, what might be the issue?
Correct Image
Rendered Image
Greetings
public class Screenshot
{
public static void TakeScreenshot(string name = null)
{
var t = new Thread((ThreadStart) delegate
{
// destination folder
var destinationFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.Create) + "\\My Software\\Screenshots";
if (!Directory.Exists(destinationFolder)) Directory.CreateDirectory(destinationFolder);
// file name
string filename = name;
if (string.IsNullOrEmpty(name))
filename = "image-" + (Directory.GetFiles(destinationFolder, "*.png").Count() + 1).ToString("000") + ".png";
// # of graphics card adapter
const int numAdapter = 0;
// # of output device (i.e. monitor)
const int numOutput = 0;
// Create DXGI Factory1
var factory = new Factory1();
var adapter = factory.GetAdapter1(numAdapter);
// Create device from Adapter
var device = new Device(adapter);
// Get DXGI.Output
var output = adapter.GetOutput(numOutput);
var output1 = output.QueryInterface<Output1>();
// Width/Height of desktop to capture
int width = ((SharpDX.Rectangle)output.Description.DesktopBounds).Width;
int height = ((SharpDX.Rectangle)output.Description.DesktopBounds).Height;
// Create Staging texture CPU-accessible
var textureDesc = new Texture2DDescription
{
CpuAccessFlags = CpuAccessFlags.Read,
BindFlags = BindFlags.None,
Format = Format.B8G8R8A8_UNorm,
Width = width,
Height = height,
OptionFlags = ResourceOptionFlags.None,
MipLevels = 1,
ArraySize = 1,
SampleDescription = { Count = 1, Quality = 0 },
Usage = ResourceUsage.Staging
};
var screenTexture = new Texture2D(device, textureDesc);
// Duplicate the output
var duplicatedOutput = output1.DuplicateOutput(device);
bool captureDone = false;
for (int i = 0; !captureDone; i++)
{
try
{
SharpDX.DXGI.Resource screenResource;
OutputDuplicateFrameInformation duplicateFrameInformation;
// Try to get duplicated frame within given time
duplicatedOutput.AcquireNextFrame(10000, out duplicateFrameInformation, out screenResource);
if (i > 0)
{
// copy resource into memory that can be accessed by the CPU
using (var screenTexture2D = screenResource.QueryInterface<Texture2D>())
device.ImmediateContext.CopyResource(screenTexture2D, screenTexture);
// Get the desktop capture texture
var mapSource = device.ImmediateContext.MapSubresource(screenTexture, 0, MapMode.Read, MapFlags.None);
// Create Drawing.Bitmap
var bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb);
var boundsRect = new System.Drawing.Rectangle(0, 0, width, height);
// Copy pixels from screen capture Texture to GDI bitmap
var mapDest = bitmap.LockBits(boundsRect, ImageLockMode.WriteOnly, bitmap.PixelFormat);
var sourcePtr = mapSource.DataPointer;
var destPtr = mapDest.Scan0;
for (int y = 0; y < height; y++)
{
// Copy a single line
Utilities.CopyMemory(destPtr, sourcePtr, width * 4);
// Advance pointers
sourcePtr = IntPtr.Add(sourcePtr, mapSource.RowPitch);
destPtr = IntPtr.Add(destPtr, mapDest.Stride);
}
// Release source and dest locks
bitmap.UnlockBits(mapDest);
device.ImmediateContext.UnmapSubresource(screenTexture, 0);
// Save the output
bitmap.Save(destinationFolder + Path.DirectorySeparatorChar + filename);
// Send Message
Main.Chat.AddMessage(null, "~b~Screenshot saved as " + filename);
// Capture done
captureDone = true;
}
screenResource.Dispose();
duplicatedOutput.ReleaseFrame();
}
catch (SharpDXException e)
{
if (e.ResultCode.Code != SharpDX.DXGI.ResultCode.WaitTimeout.Result.Code)
{
throw e;
}
}
}
});
t.IsBackground = true;
t.Start();
}
}
iam create dynamically image but can`t show in tag img
Please guide me how to set the path dynamically in View.
this my code
public class VisitCounterController : Controller
{
// GET: VisitCounter
public ActionResult Visit()
{
Response.Clear();
Response.Cache.SetNoStore();
Response.ContentType = "image/jpeg";
int length = 6;
int fontSize = 16;
int letterWidth = 15;
int letterHeight = 18;
int letterOffsetX = 2;
Color backgroundColor = Color.Black;
int number = 100;
string sNum = number.ToString().PadLeft(length, '0');
Bitmap bmp = new Bitmap(letterWidth * length + 2, letterHeight + 2);
Graphics gr = Graphics.FromImage(bmp);
gr.CompositingQuality = CompositingQuality.HighQuality;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.SmoothingMode = SmoothingMode.HighQuality;
SolidBrush bgBrush = new SolidBrush(backgroundColor);
gr.FillRegion(bgBrush, new Region(new Rectangle(0, 0, bmp.Width, bmp.Height)));
Font font = new Font("Arial", fontSize, FontStyle.Bold, GraphicsUnit.Pixel);
for (int i = 0; i <= length - 1; i++)
{
gr.DrawRectangle(Pens.LightGray, new Rectangle(i * letterWidth + 1, 1, letterWidth, letterHeight));
gr.DrawString(sNum[i].ToString(), font, Brushes.White, i * letterWidth + letterOffsetX, 1);
}
gr.DrawRectangle(Pens.Gray, new Rectangle(0, 0, letterWidth * length + 2, letterHeight + 2));
MemoryStream ms = new MemoryStream();
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return File(ms.ToArray(), "image/png");
}
iam use this code for show image but this not correct how shoved this problem thanks
<img src="~/Views/VisitCounter/Visit.cshtml" alt="Sample Image" width="300px" />
In this line you are referencing the view itself and not the controller action.
<img src="~/Views/VisitCounter/Visit.cshtml" alt="Sample Image" width="300px" />
Set the img src to #Url.Action("Visit", "VisitCounter").
<img src="#Url.Action("Visit", "VisitCounter")" alt="Sample Image" width="300px" />
my problem is a bit strange!! I'm going to create a calendar tile with writable bitmap for windows phone 8. so I'm using this character "📆".
I'm using the below code and everything works fine as I expected on emulator. but when I test my app on a real device,calendar character will be appeared different
private void RenderText9()
{
int width = 159;
int height = 159;
string imagename = "SmallBackground";
WriteableBitmap b = new WriteableBitmap(width, height);
var canvas = new Grid();
canvas.Width = b.PixelWidth;
canvas.Height = b.PixelHeight;
var background = new Canvas();
background.Height = b.PixelHeight;
background.Width = b.PixelWidth;
SolidColorBrush backColor = new SolidColorBrush((Color)Application.Current.Resources["PhoneAccentColor"]);
background.Background = backColor;
var textBlock = new TextBlock();
textBlock.Text = "25";
textBlock.TextAlignment = TextAlignment.Center;
textBlock.Margin = new Thickness(0, 72, 0, 0);
textBlock.Width = 159;
textBlock.TextWrapping = TextWrapping.Wrap;
textBlock.Foreground = new SolidColorBrush(Colors.White);
textBlock.FontSize = 35;
var textBlock2 = new TextBlock();
textBlock2.Text = "📆";
textBlock2.TextAlignment = TextAlignment.Center;
textBlock2.Margin = new Thickness(0, 40, 0, 0);
textBlock2.Width = 159;
textBlock2.TextWrapping = TextWrapping.Wrap;
textBlock2.Foreground = new SolidColorBrush(Colors.White); //color of the text on the Tile
textBlock2.FontSize = 75;
canvas.Children.Add(textBlock);
canvas.Children.Add(textBlock2);
b.Render(background, null);
b.Render(canvas, null);
b.Invalidate(); //Draw bitmap
//Save bitmap as jpeg file in Isolated Storage
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream imageStream = new IsolatedStorageFileStream("/Shared/ShellContent/" + imagename + ".jpg", System.IO.FileMode.Create, isf))
{
b.SaveJpeg(imageStream, b.PixelWidth, b.PixelHeight, 0, 100);
}
}
}
this is the tile on both emulator and real device(pay attention to difference).
anybody knows any solution??? I don't understand the reason !!
I am creating text in a GDI+ GraphicsPath, using DrawString, and then outputting this to PDF as a path.
This is all working perfectly at the moment.
The time I have an issue is when the chosen font causes the outlines to overlap each other. I have an image example though being a new user i can't upload it... (seems pointless..?..)
I found a library and also someone who has achieved the same as what I am looking for in this blog
I have converted the code snippet to vb.net though I keep getting an empty solution from the library.
Has anybody else managed to pass in a graphicsPath containing a string and retrieve outlined text using this or a similar library?
Here's some C# code that works ...
using ClipperLib;
static public void PathToPolygon(GraphicsPath path, Polygons polys, Single scale)
{
GraphicsPathIterator pathIterator = new GraphicsPathIterator(path);
pathIterator.Rewind();
polys.Clear();
PointF[] points = new PointF[pathIterator.Count];
byte[] types = new byte[pathIterator.Count];
pathIterator.Enumerate(ref points, ref types);
int i = 0;
while (i < pathIterator.Count)
{
Polygon pg = new Polygon();
polys.Add(pg);
do {
IntPoint pt = new IntPoint((int)(points[i].X * scale), (int)(points[i].Y * scale));
pg.Add(pt);
i++;
}
while (i < pathIterator.Count && types[i] != 0);
}
}
static private PointF[] PolygonToPointFArray(Polygon pg, float scale)
{
PointF[] result = new PointF[pg.Count];
for (int i = 0; i < pg.Count; ++i)
{
result[i].X = (float)pg[i].X / scale;
result[i].Y = (float)pg[i].Y / scale;
}
return result;
}
private void DrawBitmap()
{
Font f = new Font("Arial", 90);
Pen myPen = new Pen(Color.FromArgb(196, 0xC3, 0xC9, 0xCF), (float)0.6);
SolidBrush myBrush = new SolidBrush(Color.FromArgb(127, 0xDD, 0xDD, 0xF0));
path.Reset();
Polygons polys;
path.AddString("ABC", f.FontFamily, (int)f.Style, f.Size, new Point(100, 100), null);
path.Flatten();
//scale all points up by 100 because Clipper uses integer coordinates
PathToPolygon(path, polys, 100);
path.Reset();
//offset polys remembering to multiply delta by scaling amount ...
polys = Clipper.OffsetPolygons(polys, 7 * 100, JoinType.jtRound);
for (int i = 0; i < polys.Count(); i++)
{
//reverses scaling ...
PointF[] pts2 = PolygonToPointFArray(polys[i], 100);
path.AddPolygon(pts2);
}
newgraphic.FillPath(myBrush, path);
newgraphic.DrawPath(myPen, path);
}