How to perform Image comparison in Appium? - appium

I need one help.
I am using Appium and I have a scenerio wherein I need to capture an image from the app under test, preserve that image as a baseline image and then capture another image from that app under test and then perform an image comparison between these two images.
Can anyone guide me how to do this please.

This is how you do it:
#Test(dataProvider = "search")
public void eventsSearch(String data) throws InterruptedException, IOException {
Thread.sleep(2000);
boolean status = false;
//WebElement img = driver.findElementByClassName("android.widget.ImageView");
//take screen shot
File screen = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
// for (String event : events) {
driver.findElementById("your id")
.sendKeys(data);
driver.hideKeyboard();
List<WebElement> list = driver
.findElementsByXPath("//*[#class='android.widget.TextView' and #index='1']");
System.out.println(list.size());
int i = 0;
for (WebElement el : list) {
String eventList = el.getText();
System.out.println("events" + " " + eventList);
if (eventList.equals("gg")) {
status = true;
break;
}
i++;
}
//capture image of searched contact icon
List<WebElement > imageList = driver.findElementsByXPath("//*[#class='android.widget.ImageView' and #index='0']");
System.out.println(imageList.size());
System.out.println(i);
WebElement image = imageList.get(1);
Point point = image.getLocation();
//get element dimension
int width = image.getSize().getWidth();
int height = image.getSize().getHeight();
BufferedImage img = ImageIO.read(screen);
BufferedImage dest = img.getSubimage(point.getX(), point.getY(), width,
height);
ImageIO.write(dest, "png", screen);
File file = new File("Menu.png");
FileUtils.copyFile(screen, file);
//verify images
verifyImage("Menu.png", "Menu.png" );
//Assert.assertTrue(status, "FAIL Event doesn't match" + data);
}
#DataProvider(name = "search")
public Object[][] searchData() {
return new Object[][] { { "gg" } };
}
public void verifyImage(String image1, String image2) throws IOException{
File fileInput = new File(image1);
File fileOutPut = new File(image2);
BufferedImage bufileInput = ImageIO.read(fileInput);
DataBuffer dafileInput = bufileInput.getData().getDataBuffer();
int sizefileInput = dafileInput.getSize();
BufferedImage bufileOutPut = ImageIO.read(fileOutPut);
DataBuffer dafileOutPut = bufileOutPut.getData().getDataBuffer();
int sizefileOutPut = dafileOutPut.getSize();
Boolean matchFlag = true;
if(sizefileInput == sizefileOutPut) {
for(int j=0; j<sizefileInput; j++) {
if(dafileInput.getElem(j) != dafileOutPut.getElem(j)) {
matchFlag = false;
break;
}
}
}
else
matchFlag = false;
Assert.assertTrue(matchFlag, "Images are not same");
}

Related

Printing from Win RT Application (Windows 8.1 App)

I am developing a POS application in windows 8.1 (Universal App).
Order receipt will be printed from the application and even I am able to do so.
Printer - EPSON TM-U220D
Input - A grid is being created pragmatically with dynamic content within the ViewModel. So this grid is the input for printer
Output - In the print preview (Attahced pic 1) all looks good but when the receipt is actually printed then content is cut off from the end (Attahced pic 2)
PIC 1
PIC 2
Observations -
If I print a normal text file manually using print command (Right click file and then print), then all content is printed perfectly.
If I print that SAME content, from the application, by creating Dynamic grid, then with Small font size print is good but with bit bigger font size content again cuts off.
Tried -
Optimized the code for Creating Gird, by specifying height
Questions-
If preview is all good then why not output
Did anyone tried using ePOS-Print_SDK_141020E for Windows Store app?
Generate Dynamic Grid Code
private void AddRows(Grid grid, int count)
{
for (int i = 0; i < count; i++)
{
RowDefinition row = new RowDefinition();
row.Height = GridLength.Auto;
grid.RowDefinitions.Add(row);
}
}
private void AddColumns(Grid grid, int count)
{
for (int i = 0; i < count; i++)
{
grid.ColumnDefinitions.Add(new ColumnDefinition());
}
}
private TextBlock CreateTextBlock(string text, Color color, FontWeight fw, double fs = 10, int thick = 5)
{
if (color == null) color = Colors.Black;
TextBlock txtBlock1 = new TextBlock();
txtBlock1.Text = text;
txtBlock1.FontSize = fs;
txtBlock1.FontWeight = fw;
txtBlock1.Foreground = new SolidColorBrush(color);
txtBlock1.VerticalAlignment = VerticalAlignment.Center;
txtBlock1.Margin = new Thickness(thick);
return txtBlock1;
}
private async Task<Grid> CreateDynamicWPFGrid()
{
Grid ParentGrid = new Grid();
AddRows(ParentGrid, 8);
/* Start First Grid*/
Grid DynamicGrid = new Grid();
DynamicGrid.Width = 230;
DynamicGrid.HorizontalAlignment = HorizontalAlignment.Left;
DynamicGrid.VerticalAlignment = VerticalAlignment.Top;
DynamicGrid.Margin = new Thickness(24, 0, 0, 0);
AddColumns(DynamicGrid, 2);
AddRows(DynamicGrid, 3);
TextBlock txtBlock1 = CreateTextBlock(DateTime.Now.ToString("M/d/yy"), Colors.Black, FontWeights.Normal);
Grid.SetRow(txtBlock1, 0);
Grid.SetColumn(txtBlock1, 1);
.
.
.
.
Return ParentGrid;
}
Printer Events Code
//Register Print Contract
async Task RegisterPrintContract()
{
PrintManager manager = PrintManager.GetForCurrentView();
manager.PrintTaskRequested += OnPrintTaskRequested;
await PrintManager.ShowPrintUIAsync();
}
//Unregister Print Contract
void UnregisterPrintContract()
{
PrintManager printMan = PrintManager.GetForCurrentView();
printMan.PrintTaskRequested -= OnPrintTaskRequested;
}
void OnPrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
// If I need to be asynchronous, I can get a deferral. I don't *need*
// to do this here, I'm just faking it.
var deferral = args.Request.GetDeferral();
PrintTask printTask = args.Request.CreatePrintTask("My Print Job", OnPrintTaskSourceRequestedHandler);
printTask.Completed += OnPrintTaskCompleted;
deferral.Complete();
}
void OnPrintTaskCompleted(PrintTask sender, PrintTaskCompletedEventArgs args)
{
// TODO: Tidy up.
this._document = null;
this._pages = null;
}
async void OnPrintTaskSourceRequestedHandler(PrintTaskSourceRequestedArgs args)
{
var deferral = args.GetDeferral();
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
this._document = new PrintDocument();
this._document.Paginate += OnPaginate;
this._document.GetPreviewPage += OnGetPreviewPage;
this._document.AddPages += OnAddPages;
// Tell the caller about it.
args.SetSource(this._document.DocumentSource);
});
deferral.Complete();
}
void OnAddPages(object sender, AddPagesEventArgs e)
{
// Loop over all of the preview pages and add each one to add each page to be printied
// We should have all pages ready at this point...
foreach (var page in this._pages)
{
//this._pages[page.Key]
this._document.AddPage(this._pages[page.Key]);
}
PrintDocument printDoc = (PrintDocument)sender;
// Indicate that all of the print pages have been provided
printDoc.AddPagesComplete();
}
async void OnGetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
Grid x = await CreateDynamicWPFGrid();
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// NB: assuming it's ok to keep all these pages in
// memory. might not be the right thing to do
// of course.
if (this._pages == null)
{
this._pages = new Dictionary<int, UIElement>();
}
if (!this._pages.ContainsKey(e.PageNumber))
{
this._pages[e.PageNumber] = x;
}
if (this._document == null)
this._document = new PrintDocument();
this._document.SetPreviewPage(e.PageNumber, this._pages[e.PageNumber]);
}
);
}
async void OnPaginate(object sender, PaginateEventArgs e)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
() =>
{
// I have one page and that's *FINAL* !
this._document.SetPreviewPageCount(e.CurrentPreviewPageNumber, PreviewPageCountType.Final);
});
}

Android Attach Image between text with SpannableStringBuilder

Sory for my english. I want attach image from gallery and show in edit text with SpannableStringBuilder. I have success for get Image Path from Gallery. After picture selected, Picture Show. But, for the second attach image picture not show and first image attach became a text. any one give me solution ? big thanks.
this is my code:
private void IntentPict() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),MY_INTENT_CLICK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
if (requestCode == MY_INTENT_CLICK){
if (null == data) return;
String selectedImagePath;
Uri selectedImageUri = data.getData();
//there is no problem with get path
selectedImagePath = ImageFilePath.getPath(getApplicationContext(), selectedImageUri);
//pathImag is ListArray<String>
pathImg.add(selectedImagePath);
addImageBetweentext(pathImg);
}
}
}
private void addImageBetweentext(ArrayList<String> listPath) {
SpannableStringBuilder ssb = new SpannableStringBuilder();
for(int i=0;i<listPath.size();i++){
String path = listPath.get(i);
Drawable drawable = Drawable.createFromPath(path);
drawable.setBounds(0, 0, 400, 400);
ssb.append(mBodyText+"\n");
ssb.setSpan(new ImageSpan(drawable), ssb.length()-(path.length()+1),
ssb.length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
mBodyText.setText(ssb);
}
Here's something that should work. I am loading resource drawables instead, just because it was quicker for me to validate, but I tried to keep as mich as possible for your original flow and variable names:
Drawable[] drawables = new Drawable[2];
drawables[0] = getResources().getDrawable(R.drawable.img1);
drawables[1] = getResources().getDrawable(R.drawable.img2);
SpannableStringBuilder ssb = new SpannableStringBuilder();
for (int i = 0; i < drawables.length; i++) {
Drawable drawable = drawables[i];
drawable.setBounds(0, 0, 400, 400);
String newStr = drawable.toString() + "\n";
ssb.append(newStr);
ssb.setSpan(
new ImageSpan(drawable),
ssb.length() - newStr.length(),
ssb.length() - "\n".length(),
Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
mBodyText.setText(ssb);
Long story short: the start position for the incremental builder needs to be set to the current length of it, minus what you just added.

Multiple Bills Printing in C#

I am developing a module in a billing system for a national Utility. The module is supposed to pick all successfully billed customers and print their bills.Bills are written as text files and saved on a local folder and the program has to pick them up and print them one by one.I'm using a DFX-9000 printer and pre-formatted roll paper,however,each time a new bill comes in,the printer skips some space before it prints it which distorts the 2nd and following bills.
I tried putting all the bills in a single text file which prints well when opened in notepad but not in my code.
Here is part of my code
Font printFont = new Font("Lucida Console", 10);
//static string filename;
StreamReader reader = new StreamReader(Filename);
public void Print()
{
try
{
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("myPaper", 826, 1169);
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
//pd.DefaultPageSettings.PrinterSettings.IsPlotter = true;
pd.DefaultPageSettings.PrinterResolution.Kind = PrinterResolutionKind.Custom;
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
pd.Print();
if (reader != null)
reader.Close();
Console.WriteLine("Printout Complete");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void PrintTextFileHandler(object sender, PrintPageEventArgs pe)
{
StringFormat sf = new StringFormat();
Graphics g = pe.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = 40;//pe.MarginBounds.Left;
float topMargin = pe.MarginBounds.Top;
string line = null;
linesPerPage = 500;// pe.MarginBounds.Height / printFont.GetHeight(g);
while (count <= linesPerPage &&((line = reader.ReadLine()) != null))
{
yPos = topMargin + (count * printFont.GetHeight(g));
g.DrawString(line, printFont, Brushes.Black, leftMargin, yPos);
count++;
}
if (line != null)
{
pe.HasMorePages = true;
}
else
{
pe.HasMorePages = false;
}
Could your printing.papersize be wrong? I notice it's 1169, doesn't standard paper stop at 1100?

Illegal Argument Exception when trying to convert byte to Bitmap in blackberry

Here is my code where i am getting profile image bytes from twitter api,
new Thread() {
public void run() {
byte dbata[] = getBitmap(profle_pic_str);
if (dbata != null) {
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0, -1);
Bitmap image =bitmap_img.getBitmap();
final Bitmap profle_pic_bmp = image;
final Bitmap scld_bmp = new Bitmap(90, 100);
Application.getApplication().invokeLater(new Runnable() {
public void run() {
if (profle_pic_bmp != null) {
profle_pic_bmp.scaleInto(scld_bmp, Bitmap.FILTER_LANCZOS);
phot_profle.setBitmap(scld_bmp);
} else {
Dialog.alert("null");
}
}
});
// } else {
// Dialog.alert("bytes are null");
}
}
}.start();
Here i have method getBitmap(profle_pic_str); which returning bytes array of image,
public byte[] getBitmap(String url) {
Bitmap bitmap = null;
String strg = HttpConnector.getConnectionString();
byte b[] = null;
try {
b = getXML(url + strg);
} catch (IOException ie) {
ie.printStackTrace();
}
return b;
}
the url which i used is this one
http://api.twitter.com/1/users/profile_image?screen_name=screen_nameof_user&size=bigger
public byte[] getXML(String url) throws IOException {
ContentConnection connection =
(ContentConnection) javax.microedition.io.Connector.open(url);
java.io.DataInputStream iStrm = connection.openDataInputStream();
java.io.ByteArrayOutputStream bStrm = null;
byte xmlData[] = null;
try {
// ContentConnection includes a length method
int length = (int) connection.getLength();
if (length != -1) {
xmlData = new byte[length];
// Read the png into an array
// iStrm.read(imageData);
iStrm.readFully(xmlData);
} else // Length not available...
{
bStrm = new java.io.ByteArrayOutputStream();
int ch;
while ((ch = iStrm.read()) != -1) bStrm.write(ch);
xmlData = bStrm.toByteArray();
bStrm.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// Clean up
if (iStrm != null) iStrm.close();
if (connection != null) connection.close();
if (bStrm != null) bStrm.close();
}
return xmlData;
}
When i am trying to convert byte array to EncodedImage
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0, -1);
in this line of code i am getting illegal argument exception.
same code is working for Facebook profile image. I dont know why this code giving error when i am doing for twitter. Please help me friends.
try this -
EncodedImage _encoded_img = EncodedImage.createEncodedImage(dbata, 0, dbata.length);
On your code,
EncodedImage bitmap_img = EncodedImage.createEncodedImage(dbata, 0,-1);
-1 is the length of the array. Its not static. Change -1 to dbata.length.

make analog clock for blackberry

I want to make an Analog Clock In blackberry, and I want the hands of the clock to be custom images.
I gone through this thread Help with analog clock code but didnt get it worked. Can any body help me to make an analog clock
Update
The code i am getting is from the supports forum
// How to use it
ClockBitmapField clock = new ClockBitmapField(face, Field.NON_FOCUSABLE | Field.FIELD_HCENTER,
hrPng, minPng, secPng);
I can i use this to make an analog clock
How Can i use this
add(clock);
// Clock Face
class ClockBitmapField extends BitmapField {
Bitmap _face = null;
UpdateClockThread _updateClockThread = null;
Bitmap [] _hourBitmaps = null;
Bitmap [] _minBitmaps = null;
Bitmap [] _secBitmaps = null;
public ClockBitmapField(Bitmap face, long style, String [] hourPngs, String [] minPngs, String [] secPngs) {
super(face, style);
_face = face;
_ourBitmap = new Bitmap(_face.getWidth(), _face.getHeight());
this.setBitmap(_ourBitmap); // Swap to using work area
_hourBitmaps = new Bitmap [hourPngs.length];
for ( int i = 0; i < hourPngs.length; i++ ) {
_hourBitmaps[i] = Bitmap.getBitmapResource(hourPngs[i]);
}
_minBitmaps = new Bitmap [minPngs.length];
for ( int i = 0; i < minPngs.length; i++ ) {
_minBitmaps[i] = Bitmap.getBitmapResource(minPngs[i]);
}
_secBitmaps = new Bitmap [secPngs.length];
for ( int i = 0; i < secPngs.length; i++ ) {
_secBitmaps[i] = Bitmap.getBitmapResource(secPngs[i]);
}
}
protected void onDisplay() {
onExposed();
}
protected void onUnDisplay() {
onObscured();
}
protected void onExposed() {
if ( _updateClockThread == null || !_updateClockThread.isAlive() ) {
_updateClockThread = new UpdateClockThread(_ourBitmap, _face, this, _hourBitmaps, _minBitmaps, _secBitmaps);
_updateClockThread.start();
}
}
protected void onObscured() {
if ( _updateClockThread != null ) {
_updateClockThread.stop();
_updateClockThread = null;
}
}
public void invalidate() {
super.invalidate();
}
class UpdateClockThread extends Thread {
private Calendar _cal = null;
int _curHr = 0;
int _curMin = 0;
int _curSec = 0;
Bitmap _face = null;
int _faceWidth = 0;
int _faceHeight = 0;
_ourBitmap = null;
Graphics _g = null;
ClockBitmapField _ourField = null;
long LONG_ONE_THOUSAND = 1000;
boolean _stopped = false;
Bitmap [] _hourBitmaps = null;
Bitmap [] _minBitmaps = null;
Bitmap [] _secBitmaps = null;
public UpdateClockThread(Bitmap ourBitmap, Bitmap face, ClockBitmapField fieldToInvalidate,
Bitmap [] hourBitmaps, Bitmap [] minBitmaps, Bitmap [] secBitmaps) {
super();
_cal = Calendar.getInstance();
_face = face;
_faceWidth = _face.getWidth();
_faceHeight = _face.getHeight();
_ourBitmap = ourBitmap;
_g = new Graphics(_ourBitmap);
_ourField = fieldToInvalidate;
}
public void run() {
long timeToSleep = 0;
while (!_stopped) {
_g.setBackgroundColor(0x00191919);
_g.clear();
_g.drawBitmap(0, 0, _faceWidth, _faceHeight, _face, 0, 0);
_cal.setTime(new Date(System.currentTimeMillis()));
_curHr = cal.get(Calendar.HOUR);
_curMin = cal.get(Calendar.MINUTE);
_curHr = (_curHr * 5) + (5 * _curMin / 60);
if (_curHr > 60) _curHr = _curHr - 60;
_curSec = cal.get(Calendar.SECOND);
_g.drawBitmap(0, 0, _faceWidth, _faceHeight, _secBitmaps[_curSec], 0, 0);
_g.drawBitmap(0, 0, _faceWidth, _faceHeight, _minBitmaps[_curMin], 0, 0);
_g.drawBitmap(0, 0, _faceWidth, _faceHeight, _hourBitmaps[_curHr], 0, 0);
_ourField.invalidate();
timeToSleep = LONG_ONE_THOUSAND - ( System.currentTimeMillis() % LONG_ONE_THOUSAND );
if ( timeToSleep > 20 ) {
try {
Thread.sleep(timeToSleep);
} catch (Exception e) {
}
}
}
}
public void stop() {
_stopped = true;
}
}
}
and make minutes as second
thanks and regards
Just by looking at the code, it appears that the inputs:
String [] hourPngs, String [] minPngs, String [] secPngs are each a list of filenames of images which represent the clock hands at each position.
In this snippet, he builds an array of 60 Bitmaps from the strings:
_secBitmaps = new Bitmap [secPngs.length];
for ( int i = 0; i < secPngs.length; i++ ) {
_secBitmaps[i] = Bitmap.getBitmapResource(secPngs[i]);
}
Then, in this snippet you can see he gets the Bitmap object from a array by passing in the current "second" as the index:
_g.drawBitmap(0, 0, _faceWidth, _faceHeight, _secBitmaps[_curSec], 0, 0);
There doesn't appear to be any code where he rotates the images or anything.
So I guess that means you need 60 images for each clock hand. (180 images in total, plus the clock face).

Resources