I am using the following code in my event system to upload svg Images. But this gives "Parameter is not valid error" when saving the image. The following is the code I am using. Is there anything I am missing?? Any help would be really appreciated. Thanks in advance.
//only for imagaes: svg
if (mimeType.Contains("svg") && !String.IsNullOrEmpty(filename))
{
messageLog.WriteEntry("OnComponentSavePre - resizing image - for component: " + comp.Title);
// need to save first new component to be able to get type in next step
if (args.IsNewItem)
{
comp.Save();
}
BinaryContent bc = comp.BinaryContent;
var objConvertor = System.ComponentModel.TypeDescriptor.GetConverter(typeof(System.Drawing.Bitmap));
var bmpObj = (Bitmap)objConvertor.ConvertFrom(bc.GetByteArray());
//reades multimedia fields
ItemFields itemFields = new ItemFields(comp.Metadata, comp.MetadataSchema);
if (itemFields.Contains("MM_Width"))
{
NumberField width = itemFields["MM_Width"] as NumberField;
if (width != null && width.Value <= 0)
{
messageLog.WriteEntry("width = " + width.Value, EventLogEntryType.Information, 0, 0);
width.Value = bmpObj.Width;
}
}
if (itemFields.Contains("MM_Height"))
{
NumberField height = itemFields["MM_Height"] as NumberField;
if (height != null && height.Value <= 0)
{
messageLog.WriteEntry("width = " + height.Value, EventLogEntryType.Information, 0, 0);
height.Value = bmpObj.Height;
}
}
comp.Metadata = itemFields.ToXml();
messageLog.WriteEntry("metadata updated", EventLogEntryType.Information, 0, 0);
}
Related
In win2D, Get absolute mouse position is this (from Win2D Sprite Sample)
var point = e.GetCurrentPoint((UIElement)sender).Position.ToVector2();
But, This is Absolute Position,
I make whether mouse is pointing Game Player
So, I made this Code, But It doesn't work.
var rpoint = e.GetCurrentPoint(canvas).Position.ToVector2();
// 사각형 길을 보여주기
if ((rpoint.X > wizardPosition.X - 64) && (rpoint.X < wizardPosition.X + 64) && (rpoint.Y > wizardPosition.Y - 150) && (rpoint.Y < wizardPosition.Y + 42) )
{
if (ShowBorder == true) { ShowBorder = false; }
else if (ShowBorder == false)
ShowBorder = true;
}
Does anybody have solved this problem?
I have solve myself. Anyway.
The code is this
var rpoint = e.GetCurrentPoint(this).Position.ToVector2();
// Invert the display transform, to convert pointer positions into simulation rendertarget space.
Matrix3x2 Mtransform;
Matrix3x2.Invert(transform, out Mtransform);
var xpoint = Vector2.Transform(rpoint, Mtransform);
// 사각형 길을 보여주기
if ((xpoint.X > wizardPosition.X - 64) && (xpoint.X < wizardPosition.X + 64) && (xpoint.Y > wizardPosition.Y - 150) && (xpoint.Y < wizardPosition.Y + 42) )
{
if (ShowBorder == true) { ShowBorder = false; }
else if (ShowBorder == false)
ShowBorder = true;
}
I continue my work on collaborative sketch tool and trying to add retina devices support. Currently i have following behavior if user creating drawing on ipad air:
small movie
Here is my code:
this.getZoomLevel = function (height) {
if (height > 1024) {
return 1024 / height;
} else {
return height / 1024;
}
};
this.calculateCanvasSize = function(pHeight, pWidth) {
var result = {
height: 0,
width: 0
};
while (result.width < pWidth - 1 && result.height < pHeight - 1) {
result.height = result.height + 1;
result.width = result.height * 4 / 3;
}
return result;
};
this.initCanvas = function () {
try {
var parent = document.getElementsByClassName('komaso-canvas-container')[0];
var canvasSize = this.calculateCanvasSize(parent.clientHeight, parent.clientWidth);
var canvasHtml = "<div id='wrapper-" + this.Id + "' class='whiteboard-canvas-wrapper' data-ng-show='CurrentPage.Id==" + this.Id + "'><canvas width='" + canvasSize.width + "' height='" + canvasSize.height + "' id='whiteboard-" + this.Id + "' class='whiteboard'><p>Your brower does not support Canvas/p></canvas></div>";
$(parent).append($compile(canvasHtml)(scope));
this.Canvaso = document.getElementById(this.HtmlId);
if (!this.Canvaso) {
console.log('Error: Cannot find the imageView canvas element!');
return;
}
if (!this.Canvaso.getContext) {
console.log('Error: no canvas.getContext!');
return;
}
this.FabricCanvas = new fabric.Canvas(this.HtmlId, { selectionColor: 'transparent' });
this.FabricCanvas.setWidth(canvasSize.width);
this.FabricCanvas.setHeight(canvasSize.height);
fabric.Object.prototype.transparentCorners = false;
this.FabricCanvas.on('mouse:down', this.onMouseDown);
this.FabricCanvas.on('mouse:up', this.onMouseUp);
this.FabricCanvas.on('mouse:move', this.onMouseMove);
this.FabricCanvas.on('object:added', this.onObjectAdded);
this.FabricCanvas.on('text:editing:exited', self.onTextObjectEdited);
if (window.devicePixelRatio !== 1) {
var c = this.FabricCanvas.getElement();
var w = c.width, h = c.height;
c.setAttribute('width', w * window.devicePixelRatio);
c.setAttribute('height', h * window.devicePixelRatio);
$(c).width(canvasSize.width);
$(c).height(canvasSize.height);
c.getContext('2d').scale(window.devicePixelRatio, window.devicePixelRatio);
}
this.FabricCanvas.setZoom(this.getZoomLevel(this.Canvaso.height));
this.ToggleTool(self.CurrentTool.ToolName);
this.WhiteboardInitiated = true;
} catch (e) {
console.log(e);
}
};
getZoomLevel returns value to pass into SetZoom method of fabric js canvas object. We decided to have all clients canvas aspects are 4:3 and default dimension is 1024*768. So based on this dimensions we calculation zoom factor.
calculateCanvasSize - returns width and height for canvas according to 4:3 rule.
If you have any idea about how to fix this wrong behavior then post your comment please. Thank you in advance!
I would suggest you yo update to a retina enabled version of fabricjs (grab 1.6.2).
If, for any reason you can't, i think the problem is here:
if (window.devicePixelRatio !== 1) {
var c = this.FabricCanvas.getElement();
...
c.getContext('2d').scale(window.devicePixelRatio, window.devicePixelRatio);
}
getContext return a new context. This is not the context where fabric is gonna render later. If you want to have retina enabled lowerCanvas you have to scale this.FabricCanvas.contextContainer that gets created and referenced on fabric.Canvas initialization.
I suggest you to switch to newer fabric anyway.
I took standard drawHitFromCache demo (http://www.html5canvastutorials.com/kineticjs/html5-canvas-pixel-detection-with-kineticjs/) , and replaced one of images with .svg image (gray polygon) .
live demo : http://preview.yw.sk/kineticDrawHit/
source : http://preview.yw.sk/kineticDrawHit/kineticDrawHitSvg.rar
fiddle : http://jsfiddle.net/5cpyj/ - but it will not work since of local images need.
So only thing i changed is src to svg image and added 'drawHitFromCache', it works good in chromefirefox, but in internet explorer i get :
Kinetic warning: Unable to draw hit graph from cached scene canvas. SecurityError
but i use local image (monkey.svg) no external resource, why it pops SecurityError ? Since of error image is drawn but does not react on mouse enter. With png files its all right.
jq.browser - was removed from jquery, its now as plugin to jquery , + you need canvg library fo do the magic . For canvg you need at leat 207 revision with fixed draw bug . https://code.google.com/p/canvg/source/detail?r=207 , can download latest with svn installed (http://canvg.googlecode.com/svn/trunk/)
Solution to security error in warious browsers IE10+ , Safari, Ipad etc, solution use canvg to make png images for current resolution from svg images .
var pngFallbackEnabled = null;
Project.pngFallBackCheck = function () {
if (pngFallbackEnabled == null) {
if (typeof enableSvgPngFallback != 'undefined' && enableSvgPngFallback == true && typeof jq.browser != 'undefined' && (jq.browser.mobile == true || jq.browser.msie == true || jq.browser.mozilla == true)) {
pngFallbackEnabled = true;
console.log('Png fall-back enabled');
} else {
pngFallbackEnabled = false;
}
}
return pngFallbackEnabled;
};
var cachedPngImages = [];
var currentGameCanvasRatio = null;
/** Require Canvg library*/
Project.createPngImageFromSvgImage = function (svgLink, width, height, cacheIndex) {
var extension = svgLink.split('.').pop();
if (extension == "png" || extension == "jpg" || extension == "gif" || extension == "jpeg" || extension == "gif") {
return svgLink;
}
if (typeof cacheIndex != 'undefined' && typeof cachedPngImages[cacheIndex] != 'undefined') {
return cachedPngImages[cacheIndex];
}
var canvas = document.getElementById("pngDrawerCanvas");
var canvasContext = canvas.getContext('2d');
if (canvas == null) {
var canvasElement = document.createElement('canvas');
canvasElement.setAttribute("id", "pngDrawerCanvas");
canvasElement.setAttribute("width", "200");
canvasElement.setAttribute("height", "200");
canvasElement.setAttribute("style", "display: none");
document.body.appendChild(canvasElement);
canvas = document.getElementById("pngDrawerCanvas");
}
if(currentGameCanvasRatio == null){
currentGameCanvasRatio = window.module.canvas.getCurrentRatio(); /*custom function for ratio by current screen resolution*/
}
var imageWidth = Math.floor(width * currentGameCanvasRatio);
var imageHeight = Math.floor(width * currentGameCanvasRatio);
canvas.width = imageWidth;
canvas.height = imageHeight;
jq('#pngDrawerCanvas').css('width', imageWidth);
jq('#pngDrawerCanvas').css('height', imageHeight);
//canvg('pngDrawerCanvas', svgLink, 0, 0);
canvasContext.drawSvg(svgLink, 0, 0, imageWidth, imageHeight);
var img = canvas.toDataURL("image/png");
if (typeof cacheIndex != 'undefined') {
cachedPngImages[cacheIndex] = img;
}
return img;
};
I have used the below mentioned snippet to show text with image. However I am unable to display image with it.
Is the path to image not accessible from code?
C1.Win.C1FlexGrid.C1FlexGrid gAuditL = new C1.Win.C1FlexGrid.C1FlexGrid();
.
.
.
gAuditL.DataSource = AuditLogVieweryDT;// this is datasource
for (int i = gAuditL.Row.Fixed; i < gAuditL.Rows.Count; i++)
//foreach row in grid
{
string severity = gAuditL[i, gAuditL.Cols["Severity"].Index].ToString();
if (severity == "Information")
{
this.gAuditL.SetCellImage(i, 0,Image.FromFile(#".\\Resources\information.bmp"));
this.gAuditL.SetData(i, 0, "Information");
}
if (severity == "Warning")
{
this.gAuditL.SetCellImage(i, 0, Image.FromFile(#".\\Resources\warning.bmp"));
this.gAuditL.SetData(i, 0, "Warning");
}
if (severity == "Critical")
{
this.gAuditL.SetCellImage(i, 0, Image.FromFile(#".\\Resources\critical.bmp"));
this.gAuditL.SetData(i, 0, "Critical");
}
if (severity == "Unspecified")
{
this.gAuditL.SetCellImage(i, 0, Image.FromFile(#".\\Resources\unspecified.bmp"));
this.gAuditL.SetData(i, 0, "Unspecified");
}
this.gAuditL.Styles.Normal.ImageAlign = C1.Win.C1FlexGrid.ImageAlignEnum.LeftCenter;
this.gAuditL.Styles.Normal.TextAlign = C1.Win.C1FlexGrid.TextAlignEnum.RightCenter;
}
Please refer this.(Answer posted by OP)
namespace SampleProject.Forms.Maintenance
{
public partial class SampleProject: Form
{
Image img1, img2, img3, img4;// declare member variable
//Load Event
private void AuditLogViewer_Load(object sender, EventArgs e)
{
object information = Resources.ResourceManager.GetObject("information"); //Return an object from the image chan1.png in the project
img1 = (Image)information;
object Warning = Resources.ResourceManager.GetObject("warning"); //Return an object from the image chan1.png in the project
img2 = (Image)Warning;
object critical = Resources.ResourceManager.GetObject("critical"); //Return an object from the image chan1.png in the project
img3 = (Image)critical;
object unspecified = Resources.ResourceManager.GetObject("unspecified"); //Return an object from the image chan1.png in the project
img4 = (Image)unspecified;
}
//Grid Click Event
private void grdAuditLogs_OwnerDrawCell(object sender, OwnerDrawCellEventArgs e)
{
if (e.Col == 2)
{
//let the grid paint the background and border for the cell
e.DrawCell(C1.Win.C1FlexGrid.DrawCellFlags.Background | C1.Win.C1FlexGrid.DrawCellFlags.Border);
//find text width
var width = (int)e.Graphics.MeasureString(e.Text, e.Style.Font).Width;
//x-coordinate for each image
var img1_x = e.Bounds.X + width + 10;
var img2_x = e.Bounds.X + width + 10;
var img3_x = e.Bounds.X + width + 10;
var img4_x = e.Bounds.X + width + 10;
//var img3_x = img2_x + img2.Width + 5;
//location for each image
var img1_loc = new Point(img1_x, e.Bounds.Y + img1.Height - 18);
var img2_loc = new Point(img2_x, e.Bounds.Y + img2.Height - 18);
var img3_loc = new Point(img3_x, e.Bounds.Y + img3.Height - 18);
var img4_loc = new Point(img4_x, e.Bounds.Y + img4.Height - 18);
//draw images at aforementioned points
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Information")
e.Graphics.DrawImage(img1, img1_loc);
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Warning")
e.Graphics.DrawImage(img2, img2_loc);
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Critical")
e.Graphics.DrawImage(img3, img3_loc);
if (grdAuditLogs[e.Row, grdAuditLogs.Cols["Severity"].Index].ToString() == "Unspecified")
e.Graphics.DrawImage(img4, img4_loc);
//e1.Graphics.DrawImage(img3, img3_loc);
//draw text
e.Graphics.DrawString(e.Text, e.Style.Font, Brushes.Black, e.Bounds.Location);
e.Handled = true;
}
}
I am trying to save generate and save the barcode in excel. However, I am having problem saving the image in the correct format. The image is saved in the last column. But, I am not sure how save it.
hope someone can help. Code as below:
<?php
require_once '../app/Mage.php';
umask(0);
Mage::app();
Mage::app()->loadArea(Mage_Core_Model_App_Area::AREA_FRONTEND);
header("Content-type:text/octect-stream");
header("Content-Disposition:attachment;filename=exportMyEANCodes.csv");
$eanPrefixCode="0123456";
$storeId = Mage::app()->getStore()->getId();
$product = Mage::getModel('catalog/product');
$products = $product->getCollection()->addStoreFilter($storeId)->getAllIds();
echo '"sku","ean","barcode"'. "\n";
foreach($products as $productid)
{
$product = Mage::getModel('catalog/product')->load($productid);
$sku = $product->getSku();
$ean=ean13_check_digit($eanPrefixCode. str_pad($product->getId(), 5, "0", STR_PAD_LEFT));
$bc = new barCode();
//$bc->build($ean);
$output='"'. $sku. '","'. $ean. '","'.$bc->build($ean).'"';
echo $output. "\n";
}
$bc = new barCode();
$bc->build($ean);
function ean13_check_digit($digits){
$digits =(string)$digits;
$even_sum = $digits{1} + $digits{3} + $digits{5} + $digits{7} + $digits{9} + $digits{11};
$even_sum_three = $even_sum * 3;
$odd_sum = $digits{0} + $digits{2} + $digits{4} + $digits{6} + $digits{8} + $digits{10};
$total_sum = $even_sum_three + $odd_sum;
$next_ten = (ceil($total_sum/10))*10;
$check_digit = $next_ten - $total_sum;
return $digits . $check_digit;
}
class barCode
{
public $bcHeight, $bcThinWidth, $bcThickWidth, $bcFontSize, $mode;
function __construct($mode='gif', $height=50, $thin=2, $thick=3, $fSize=2)
{
$this->bcHeight = $height;
$this->bcThinWidth = $thin;
$this->bcThickWidth = $this->bcThinWidth * $thick;
$this->fontSize = $fSize;
$this->mode = $mode;
$this->outMode = array('gif'=>'gif', 'png'=>'png', 'jpeg'=>'jpeg', 'wbmp'=>'vnd.wap.wbmp');
$this->codeMap = array(
'0'=>'010000101', '1'=>'100100001', '2'=>'001100001', '3'=>'101100000',
'4'=>'000110001', '5'=>'100110000', '6'=>'001110000', '7'=>'000100101',
'8'=>'100100100', '9'=>'001100100', 'A'=>'100001001', 'B'=>'001001001',
'C'=>'101001000', 'D'=>'000011001', 'E'=>'100011000', 'F'=>'001011000',
'G'=>'000001101', 'H'=>'100001100', 'I'=>'001001100', 'J'=>'000011100',
'K'=>'100000011', 'L'=>'001000011', 'M'=>'101000010', 'N'=>'000010011',
'O'=>'100010010', 'P'=>'001010010', 'Q'=>'000000111', 'R'=>'100000110',
'S'=>'001000110', 'T'=>'000010110', 'U'=>'110000001', 'V'=>'011000001',
'W'=>'111000000', 'X'=>'010010001', 'Y'=>'110010000', 'Z'=>'011010000',
' '=>'011000100', '$'=>'010101000', '%'=>'000101010', '*'=>'010010100',
'+'=>'010001010', '-'=>'000110100', '.'=>'110000100', '/'=>'010100010'
);
}
public function build($text='', $showText=true, $fileName=null)
{
if (trim($text) <= ' ')
throw new exception('barCode::build - must be passed text to operate');
if (!$fileType = $this->outMode[$this->mode])
throw new exception("barCode::build - unrecognized output format ({$this->mode})");
if (!function_exists("image{$this->mode}"))
throw new exception("barCode::build - unsupported output format ({$this->mode} - check phpinfo)");
$text = strtoupper($text);
$dispText = "* $text *";
$text = "*$text*"; // adds start and stop chars
$textLen = strlen($text);
$barcodeWidth = $textLen * (2 * $this->bcThinWidth + 3 * $this->bcThickWidth) - $this->bcThinWidth;
$im = imagecreate($barcodeWidth, $this->bcHeight);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
imagefill($im, 0, 0, $white);
$xpos = 0;
for ($idx=0; $idx<$textLen; $idx++)
{
if (!$char = $text[$idx]) $char = '-';
for ($ptr=0; $ptr<=8; $ptr++)
{
$elementWidth = ($this->codeMap[$char][$ptr]) ? $this->bcThickWidth : $this->bcThinWidth;
if (($ptr + 1) % 2)
imagefilledrectangle($im, $xpos, 0, $xpos + $elementWidth-1, $this->bcHeight, $black);
$xpos += $elementWidth;
}
$xpos += $this->bcThinWidth;
}
if ($showText)
{
$pxWid = imagefontwidth($this->fontSize) * strlen($dispText) + 10;
$pxHt = imagefontheight($this->fontSize) + 2;
$bigCenter = $barcodeWidth / 2;
$textCenter = $pxWid / 2;
imagefilledrectangle($im, $bigCenter - $textCenter, $this->bcHeight - $pxHt, $bigCenter + $textCenter, $this->bcHeight, $white);
imagestring($im, $this->fontSize, ($bigCenter - $textCenter) + 5, ($this->bcHeight - $pxHt) + 1, $dispText, $black);
}
$badMode = false;
if (!$fileName) header("Content-type: image/{$fileType}");
switch($this->mode)
{
case 'gif':
imagegif($im, $fileName);
break;
case 'png':
imagepng($im, $fileName);
break;
case 'jpeg':
imagejpeg($im, $fileName);
break;
case 'wbmp':
imagewbmp($im, $fileName);
break;
default:
$badMode = true;
}
imagedestroy($im);
if ($badMode)
throw new Exception("barCode: Unknown Graphics Type '{$this->mode}'");
}
}
?>
I did some testing and I, too, saw a lot of those same characters!
Perhaps an alternative method: Have your script output the desired CSV file, but in the 3rd field, make a URL. You could make a small script in var/export/sku.php:
<?php
require_once '../../app/Mage.php';
umask(0);
Mage::app();
Mage::app()->loadArea(Mage_Core_Model_App_Area::AREA_FRONTEND);
if( isset($_GET['sku']) && strlen($_GET['sku']) > 5 ) {
header('Content-Type: image/jpeg');
$barcodeOptions = array('text' => $_GET['sku']);
$rendererOptions = array();
$imageResource = Zend_Barcode::draw(
'code39', 'image', $barcodeOptions, $rendererOptions
);
imagejpeg($imageResource);
} ?>
Then in your script, you have (sku),ean,http://yoursite.com/var/export/sku.php?sku=(sku) There is a way to have the spreadsheet load the images -- though I haven't done this personally, I have seen links displayed as embedded images.
My sample above outputs a code39 barcode, which is scannable. You can replace with your own image generation. This is why I asked if you saw barcodes, as I haven't output rendered images like this before.