TwainDotNet specific area scan - area

In my application I am using TwainDotNet library and I am scanning a specific area from flatbed.
public Prasymas scanForm(Prasymas prasymas, bool isItFirstScan)
{
Enabled = false;
_settings = new ScanSettings();
_settings.UseDocumentFeeder = false;
_settings.ShowTwainUI = false;
_settings.ShowProgressIndicatorUI = true;
_settings.UseDuplex = false;
_settings.Resolution =
false
? ResolutionSettings.Fax : ResolutionSettings.ColourPhotocopier;
_settings.Page = PageSettings.Default;
if (!isItFirstScan)
{
_prasymas = prasymas;
AreaSettings = new AreaSettings(Units.Centimeters, 0.0f, 0.0f, (float)(_prasymas.maxScanAukstis), 0.0f);
}
else
{
_settings.Area = !false ? null : AreaSettings;
}
_settings.ShouldTransferAllPages = true;
_settings.Rotation = new RotationSettings()
{
AutomaticRotate = false,
AutomaticBorderDetection = false
};
try
{
_twain.SelectSource();
_twain.StartScanning(_settings);
}
catch (TwainException ex)
{
if (ex.Message == "Error opening data source")
{
_twain.SelectSource();
scanForm(_prasymas, isItFirstScan);
Enabled = true;
}
else
throw ex;
}
catch (Exception exc)
{
if (exc.Message == "Pasiuto skeneris")
{
scanForm(_prasymas, true);
}
else
throw exc;
}
Enabled = true;
return prasymas;
}
but in result when scanning starts and a scan source is Twain driver it scans full page, but if I choose WIA driver I get specifically selected area.
Main Idea is then App starts for the first time it scans full page, next time it scans only specific height of the page.

After reading documentation I found out that just needed to comment out rotation part and everything started to work. I can scan selected area.

Related

html/css-/js drag and drop for mouse and touch combine with rotate with every click?

I use a script for moving an object both with mouse and touch screen. This works.
I have another script to make the object rotate 90 degrees with each click, this also works.
It just doesn't work together.
When I merge them, the move still works, but with a click the object moves back to the starting position and only rotates there.
I've read that I should merge this but I don't know how. Below both scripts.
Thanks in advance for responses.
var container = document.querySelector("#container");
var activeItem = null;
var active = false;
container.addEventListener("touchstart", dragStart, false);
container.addEventListener("touchend", dragEnd, false);
container.addEventListener("touchmove", drag, false);
container.addEventListener("mousedown", dragStart, false);
container.addEventListener("mouseup", dragEnd, false);
container.addEventListener("mousemove", drag, false);
function dragStart(e) {
if (e.target !== e.currentTarget) {
active = true;
// this is the item we are interacting with
activeItem = e.target;
if (activeItem !== null) {
if (!activeItem.xOffset) {
activeItem.xOffset = 0;
}
if (!activeItem.yOffset) {
activeItem.yOffset = 0;
}
if (e.type === "touchstart") {
activeItem.initialX = e.touches[0].clientX - activeItem.xOffset;
activeItem.initialY = e.touches[0].clientY - activeItem.yOffset;
} else {
console.log("doing something!");
activeItem.initialX = e.clientX - activeItem.xOffset;
activeItem.initialY = e.clientY - activeItem.yOffset;
}
}
}
}
function dragEnd(e) {
if (activeItem !== null) {
activeItem.initialX = activeItem.currentX;
activeItem.initialY = activeItem.currentY;
}
active = false;
activeItem = null;
}
function drag(e) {
if (active) {
if (e.type === "touchmove") {
e.preventDefault();
activeItem.currentX = e.touches[0].clientX - activeItem.initialX;
activeItem.currentY = e.touches[0].clientY - activeItem.initialY;
} else {
activeItem.currentX = e.clientX - activeItem.initialX;
activeItem.currentY = e.clientY - activeItem.initialY;
}
activeItem.xOffset = activeItem.currentX;
activeItem.yOffset = activeItem.currentY;
setTranslate(activeItem.currentX, activeItem.currentY, activeItem);
}
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
// Make blocks rotate 90 deg on each click
var count=0;
function rot(e){
count++;
var deg=count*90;
e.style.transform = "rotate("+deg+"deg)";
}
So I put them in a file but then it only works as described above.

Xamarin-CrossDownloadManager - waiting for download file

I use Xamarin-CrossDownloadManager (https://github.com/SimonSimCity/Xamarin-CrossDownloadManager) and I need waiting for download a file. I have this code:
private static async Task<bool> FileDownloadedTest(string LinkToFile, string PathFile)
{
var downloadManager = CrossDownloadManager.Current;
CrossDownloadManager.Current.PathNameForDownloadedFile = new System.Func<IDownloadFile, string>(file => {
return PathFile;
});
{
await DeleteFile(PathFile);
var file = downloadManager.CreateDownloadFile(LinkToFile);
await Task.Run(() => downloadManager.Start(file, true)); //why this not wait???
}
bool FileExist = await IsFileExist(PathFile);
return FileExist;
}
Why it not wait for finish download action? How to do it?
On library site they wrote, that I can watch the IDownloadManager.Queue to get information when the file is downloaded. But, I don't know how to use this in my method... Can you help me?
PS: Sorry for my english, I'm still learning it ;)
With that library, there is no callback or event published for when a file is finished downloading, but you can do a simple check and wait some more loop.
await Task.Run(async () =>
{
var downloadManager = CrossDownloadManager.Current;
var file = downloadManager.CreateDownloadFile(someFileBasedUrl);
downloadManager.Start(file);
bool isDownloading = true;
while (isDownloading)
{
await Task.Delay(10 * 1000);
isDownloading = IsDownloading(file);
}
});
The IsDownloading method:
bool IsDownloading(IDownloadFile file)
{
if (file == null) return false;
switch (file.Status)
{
case DownloadFileStatus.INITIALIZED:
case DownloadFileStatus.PAUSED:
case DownloadFileStatus.PENDING:
case DownloadFileStatus.RUNNING:
return true;
case DownloadFileStatus.COMPLETED:
case DownloadFileStatus.CANCELED:
case DownloadFileStatus.FAILED:
return false;
default:
throw new ArgumentOutOfRangeException();
}
}
Re: https://github.com/SimonSimCity/Xamarin-CrossDownloadManager/blob/develop/Sample/DownloadExample/Downloader.cs#L46
I don't know why IDownloadFile.Status = COMPLETED not working, but i found solve problem:
await Task.Run(() =>
{
var downloadManager = CrossDownloadManager.Current;
var file = downloadManager.CreateDownloadFile(LinkToFile);
downloadManager.Start(file);
while (file.Status == DownloadFileStatus.INITIALIZED)
{
while (file.TotalBytesExpected > file.TotalBytesWritten)
{
Debug.WriteLine(file.Status);
}
}
});
Somebody know why DownloadFileStatus.INITIALIZED working, but DownloadFileStatus.COMPLETED not?
SushiHangover's answer above worked great, and I combined it with ACR User Dialog's package (https://github.com/aritchie/userdialogs) to show a nice loading progress screen to the user while waiting for the download to complete. This works nicely on Android (I couldn't test iOS yet).
...
var downloadManager = CrossDownloadManager.Current;
var fileToDownload = downloadManager.CreateDownloadFile(args.Url);
downloadManager.Start(fileToDownload, true);
args.Cancel = true;
UserDialogs.Instance.Progress("Downloading").Show();
bool isDownloading = true;
while (isDownloading)
{
await Task.Delay(100);
if (fileToDownload.TotalBytesExpected > 0)
{
UserDialogs.Instance.Progress().PercentComplete = (int)(fileToDownload.TotalBytesWritten / fileToDownload.TotalBytesExpected * 100);
Console.WriteLine(("DOWNLOAD PROGRESS: " + fileToDownload.TotalBytesWritten / fileToDownload.TotalBytesExpected * 100).ToString() + "%");
}
isDownloading = IsDownloading(fileToDownload);
}
UserDialogs.Instance.Progress().Hide();
//Below code opens the download location after download has completed.
Intent intent = new Intent(DownloadManager.ActionViewDownloads);
intent.AddFlags(ActivityFlags.NewTask);
Android.App.Application.Context.StartActivity(intent);
return;
}
}
}
bool IsDownloading(IDownloadFile file)
{
if (file == null) return false;
switch (file.Status)
{
case DownloadFileStatus.INITIALIZED:
case DownloadFileStatus.PAUSED:
case DownloadFileStatus.PENDING:
case DownloadFileStatus.RUNNING:
return true;
case DownloadFileStatus.COMPLETED:
case DownloadFileStatus.CANCELED:
case DownloadFileStatus.FAILED:
return false;
default:
throw new ArgumentOutOfRangeException();
}
}

Dynamic web twain version 10.0

if i run my code in mozilla firefox after i click scan in UI select source window is opened and then it crashed.
bt the same code if i run on chrome it scan the image in the scanner after that if i click the scan on the new window it scan properly and crashed during file transfer and chrome tell a error message "a plugin (shockwave flash) isnt responding "
what may be the prob
function onScan(no_of_pages)
{
if (DWObject)
{
if (DWObject.SourceCount > 0)
{
DWObject.SelectSource();
DWObject.IfDisableSourceAfterAcquire = true;
DWObject.AcquireImage();
DWObject.MaxImagesInBuffer = no_of_pages;
}
else
alert("No TWAIN compatible drivers detected.");
}
}
function Dynamsoft_ChangeConfig(config){
config.onPrintMsg = g_DWT_PrintMsg;
}
function g_DWT_PrintMsg(strMessage) {
alert(strMessage);
}
function OnPostTransferCallback()
{
try{
if(DWObject.MaxImagesInBuffer == DWObject.HowManyImagesInBuffer)
{
DWObject.CloseSource();
sendToFlash() ;
}else
{
//TBD
}
}catch(err){
alert(err.message);
}
}
//Call back function from the
function sendToFlash()
{
try{
var flashMovie = window.document.flashContent;
flashMovie.sendToActionScript(DWObject.HowManyImagesInBuffer);
//document.getElementById("ICANSWF").sendToActionScript();
}catch(err){
alert(err.message);
}
}
//call from flash for uploading documents
function onUpload(serialNo)
{
//alert("upload the file");
var imageArr = new Array();
try{
var imageName;
var uploadPage;
var serverHost;
var CurrentPathName = unescape(location.pathname); // get current PathName in plain ASCII
var CurrentPath = CurrentPathName.substring(0, CurrentPathName.lastIndexOf("/") + 1);
uploadPage = CurrentPath+"TempUpload.php";
//uploadPage = CurrentPath+"UploadDocument.php";
//serverHost = "blabla";
//window.Plugin.HTTPPort =1451;
serverHost = "our host";
DWObject.HTTPPort = 80;
DWObject.IfSSL = false;
//alert(Plugin.HowManyImagesInBuffer);
for(var i=0;i < DWObject.HowManyImagesInBuffer;i++)
{
imageName = serialNo+"_"+(i+1)+".png";
DWObject.HTTPUploadThroughPost(serverHost,i,uploadPage,imageName);
if (DWObject.ErrorCode == 0)
{
//alert(imageName);
imageArr.push({"label":imageName,"source":"http://"+serverHost+":"+DWObject.HTTPPort+"/icanindonesia/AppData/Temp/"+imageName}); //Push image name and location in an array
}
else //succeded
{
alert(DWObject.ErrorString);
//imageArr[i] = imageName;
//alert(imageArr[i]);
}
}
}catch(err){
//alert("onUpload");
alert(err.message);
}
console.log(imageArr);
return imageArr;
}
function startDownload(url)
{
//var url='.zip';
window.open(url,'Download');
}
function openDocument(url){
window.open(url, '_blank',"ican image viewer");
}
#priya, this is Rachel from Dynamsoft.Thanks for using our Dynamic Web TWAIN SDK. Which version of Firefox and Chrome are you using? We now also have newer version of Dynamic Web TWAIN which you may try. Please contact our support team to get better help.

a puzzle game algorithm in as3

I am creating game like http://www.puzzlegames.org/814games-Connect-2-Game-game.html. so what should i add in connected() function?
fB and sB are First and second button selected.
fBN and sBN are names of those buttons.
allNull() makes fB,sB, fBN, sBN null.
function onClick(e:MouseEvent):void {
if (! another) {
another = true;
fB = e.target;
fBN = e.target.name;
}
else {
sB = e.target;
sBN = e.target.name;
if (fBN == sBN)
{
allNull();
}
else if (connected())
{
fB.removeEventListener(MouseEvent.MOUSE_DOWN, onClick);
sB.removeEventListener(MouseEvent.MOUSE_DOWN, onClick);
fB.alpha = 0;
sB.alpha = 0;
pairCount++;
allNull();
if (pairCount == 25)
{
gameOver = false;
showScore();
endGame();
}
}
another = false;
}
}
Please help. I am trying to solve this problem since 15 days.
Thanks in advance.

In Selenium, how to compare images?

As i have been asked to automate our Company's website using Selenium Automation tooL.
But i am new to Selenium tool to proceed with, but i have learnt the basics of Selenium IDE and RC. But i am very much confused with how to compare actual and original images as we usually do in other automation tools. How do we come to a result that there bug in the website? Its obviously through image comparison but i wonder as selenium is one of the very popular tools but it doesn't have image comparing option. On the other hand i doubt whether my way of proceeding with the automation process is correct! Could somebody please help me out..
Thanks in Advance!!
Sanjay S
I had simillar task. I needed to compare more than 3000 images on a WebPage.
First of all I scrolled page to load all images:
public void compareImage() throws InterruptedException {
driver.get(baseUrl);
driver.manage().window().maximize();
JavascriptExecutor executor = (JavascriptExecutor) driver;
Long previousHeight;
Long currentHeight;
do {
previousHeight = (Long) executor.executeScript("return document.documentElement.scrollHeight");
executor.executeScript("window.scrollBy(0, document.documentElement.scrollHeight)");
Thread.sleep(500);
currentHeight = (Long) executor.executeScript("return document.documentElement.scrollHeight");
} while (Long.compare(previousHeight, currentHeight) != 0);
after I compared size of all images with first image(or you can just write size):
List<WebElement> images = driver.findElements(By.cssSelector("img[class='playable']"));
List<String> errors = new LinkedList<>();
int imgWidth, imgHeight, elWidth, elHeight;
int imgNum = 0;
imgWidth = images.get(0).getSize().getWidth();
imgHeight = images.get(0).getSize().getHeight();
for (WebElement el : images) {
imgNum++;
elWidth = el.getSize().getWidth();
elHeight = el.getSize().getHeight();
if (imgWidth != elWidth || imgHeight != elHeight) {
errors.add(String.format("Picture # %d has incorrect size (%d : %d) px"
, imgNum, elWidth, elHeight));
}
}
for (String str : errors)
System.out.println(str);
if (errors.size() == 0)
System.out.println("All images have the same size");
}
Since you mention knowledge about Selenium RC, you can easily extend Selenium's capability using a library for your chosen programming language. For instance, in Java you can use the PixelGrabber class for comparing two images and assert their match.
imagemagick and imagediff are also two good tools to use for image matching. You would require Selenium RC and a programming language knowledge to work with it.
Image comparison on C#. To get exact results I recommend to disable anti aliasing browser feature before taking screenshots, otherwise pixels each time are a little bit different drawn. For example HTML canvas element options.AddArgument("disable-canvas-aa");
private static bool ImageCompare(Bitmap bmp1, Bitmap bmp2, Double TolerasnceInPercent)
{
bool equals = true;
bool flag = true; //Inner loop isn't broken
//Test to see if we have the same size of image
if (bmp1.Size == bmp2.Size)
{
for (int x = 0; x < bmp1.Width; ++x)
{
for (int y = 0; y < bmp1.Height; ++y)
{
Color Bitmap1 = bmp1.GetPixel(x, y);
Color Bitmap2 = bmp2.GetPixel(x, y);
if (Bitmap1.A != Bitmap2.A)
{
if (!CalculateTolerance(Bitmap1.A, Bitmap2.A, TolerasnceInPercent))
{
flag = false;
equals = false;
break;
}
}
if (Bitmap1.R != Bitmap2.R)
{
if (!CalculateTolerance(Bitmap1.R, Bitmap2.R, TolerasnceInPercent))
{
flag = false;
equals = false;
break;
}
}
if (Bitmap1.G != Bitmap2.G)
{
if (!CalculateTolerance(Bitmap1.G, Bitmap2.G, TolerasnceInPercent))
{
flag = false;
equals = false;
break;
}
}
if (Bitmap1.B != Bitmap2.B)
{
if (!CalculateTolerance(Bitmap1.B, Bitmap2.B, TolerasnceInPercent))
{
flag = false;
equals = false;
break;
}
}
}
if (!flag)
{
break;
}
}
}
else
{
equals = false;
}
return equals;
}
This C# function calculates tolerance
private static bool CalculateTolerance(Byte FirstImagePixel, Byte SecondImagePixel, Double TolerasnceInPercent)
{
double OneHundredPercent;
double DifferencesInPix;
double DifferencesPercentage;
if (FirstImagePixel > SecondImagePixel)
{
OneHundredPercent = FirstImagePixel;
}
else
{
OneHundredPercent = SecondImagePixel;
}
if (FirstImagePixel > SecondImagePixel)
{
DifferencesInPix = FirstImagePixel - SecondImagePixel;
}
else
{
DifferencesInPix = SecondImagePixel - FirstImagePixel;
}
DifferencesPercentage = (DifferencesInPix * 100) / OneHundredPercent;
DifferencesPercentage = Math.Round(DifferencesPercentage, 2);
if (DifferencesPercentage > TolerasnceInPercent)
{
return false;
}
return true;
}

Resources