using camera2 api i m save file like this
if (Build.VERSION.SDK_INT <=Build.VERSION_CODES.P){
final String folderPath = Environment.getExternalStorageDirectory() + "/Pikpap/";
file1 = new File(folderPath);
} else{
file1 = new File( CameraFragment.view.getContext().getExternalFilesDir()+ "/Pikpap/");
}
if (!file1.exists()) {
file1.mkdirs();
}
String fullName = file1.getAbsolutePath() + "Pikpap" + currentTime+name + ".jpg";
File file = new File(fullName);
but some time file not save and image blank set on image view
this issue created on all devices
I'm trying to add a screenshot to my ExtentReport HTML file, but for some reason, the image is not there even though it DOES exist and the console shows that it's looking at the correct place (href is correct).
This is the latest trial code:
Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
String destination = getScreenshotPath();
ImageIO.write(screenshot.getImage(), "IMG", new File(destination));
test.fail("Details: " + test.addScreenCaptureFromPath(destination));
The screenshot gets saved in the destination.
When I try the debugging mode, or look at the report, it's printed as:
Details: com.aventstack.extentreports.ExtentTest#62041567
and there's a broken image under it:
As suggested - the absolute path could be a solution, but I didn't want to go that way.
I've figured out that a solution is to store the images in the same directory where the report gets generated, give the image name to .addScreenCaptureFromPath(screenshotName.PNG) and it works perfectly.
I used the absolute path
Note: inspects the broken image from the browser to validate the absolute path of the image
Take ScreenShot:
public static String TakesScreenshot(IWebDriver driver, string FileName)
{
string pathProject = AppDomain.CurrentDomain.BaseDirectory;
string pathScreen = pathProject.Replace("\\bin\\Debug", "");
string path = pathScreen + "project/Test-output/Images/";
StringBuilder TimeAndDate = new StringBuilder(DateTime.Now.ToString());
TimeAndDate.Replace("/", "_");
TimeAndDate.Replace(":", "_");
TimeAndDate.Replace(" ", "_");
string imageName = FileName + TimeAndDate.ToString();
((ITakesScreenshot)driver).GetScreenshot().SaveAsFile(path + "_" + imageName + "." + System.Drawing.Imaging.ImageFormat.Jpeg);
return path + "_" + imageName + "." + "jpeg";
}
Attach image to the report with path of the preview method:
In the specific step:
ExtentTest.Fail("message", MediaEntityBuilder.CreateScreenCaptureFromPath(TakeScreenShot.TakesScreenshot(driver, "Fatal")).Build());
With the method "TakesScreenshot" Take the screenshot
Version ExtentReport: 3,
C#,
NUnit 3
USING JAVA:
<dependency>
<groupId>com.relevantcodes</groupId>
<artifactId>extentreports</artifactId>
<version>2.41.2</version>
</dependency>
Is:
ExtentTestManager.getTest().log(LogStatus.ERROR, ExtentTestManager.getTest().addScreenCapture("//ABOLUTE/PATH/IMAGE.PNG"));
regards.
In order to get screenshot in the extent report just add a extra dot in the extent report screenshot path. Refer code below:
test.log(Status.INFO, "FAQs button clicked",
MediaEntityBuilder.createScreenCaptureFromPath("." + screenshot()).build());
Hope this helps!
You can add screenshot for absolute path as below:
File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
//for file copy, absolute path starts from your project directory
FileUtils.copyFile(src, new File("../resources/reports/screenshots/screen2.png"));
String img = logger.addScreenCapture("./screenshots/screen2.png");
logger.log(LogStatus.PASS, "Title verified...", img);
Please note that here in addScreenCapture() method path started from screenshots folder and not resources as in copyFile() method. Its because ExtentReports is initialized as :
ExtentReports report = new ExtentReports("../resources/reports/extentreports_v2.html", true);
so for extentreports_v2.html to find screenshot's absolute path, it should start from "reports" directory
This is will work for you as its works me as well.
public void afterScenario(Scenario scenario) throws IOException {
if (scenario.isFailed()) {
String screenshotName = scenario.getName().replaceAll(" ", "_");
//This takes a screenshot from the driver at save it to the specified location
File sourcePath = ((TakesScreenshot) testContext.getWebDriverManager().getDriver()).getScreenshotAs(OutputType.FILE);
//Building up the destination path for the screenshot to save
//Also make sure to create a folder 'screenshots' with in the cucumber-report folder
File destinationPath = new File("./src/test/resources/"+screenshotName + ".png");
//Copy taken screenshot from source location to destination location
Files.copy(sourcePath, destinationPath);
//This attach the specified screenshot to the test
Reporter.addScreenCaptureFromPath(screenshotName+".png");
System.out.println("Cant take screenshot in grid.");
}
}
I tried various sites and blogs for this issue, but couldn't get a solution anywhere. I got below solution after trying various approaches. Try the below solution and it worked perfectly for me.
public static synchronized String addScreenshots(){
WebDriver webDriver = Browser.getDriver();
Long l = Calendar.getInstance().getTimeInMillis();
String screenshotId = l.toString();
String Path = System.getProperty("user.dir")+"/ExtentReports/";
File screenshot = ((TakeScreenshot)WebDriver).getScreenshotAs(OutputType.FILE);
String imgPath = Path+screenshotId+".png";
File dest = new File(imgPath);
try {
FileUtils.copyFile(screenShot, dest);
} catch (IOException e) {
e.printStackTrace();
}
String ImagePath = "../ExtentReports/"+screenshotId+".png";
return ImagePath;
}
I tried the following code, and it resulted in a screenshot being recorded in the report.
File file = new File("./Screenshots/" + result.getName() + ".png");
String absolutePath = file.getAbsolutePath();
logger.fail("details", MediaEntityBuilder.createScreenCaptureFromPath(absolutePath).build());
The below piece of code can solve your problem:
public void reportStatus(ITestResult result){
if(result.getStatus()==ITestResult.FAILURE){
String screenshotFilePath=takeScreenshotMethod(driver, result.getName());
extentTest.log(Status.FAIL, "Screenshot", MediaEntityBuilder.createScreenCaptureFromPath(screenshotFilePath).build());
}
}
public static void TakeScreenshot(Status status, string stepDetail)
{
string path = #"C:\ExtentReports\" + "TestExecLog_" + DateTime.Now.ToString("yyyyMMddHHmmss");
Screenshot image = ((ITakesScreenshot)driver).GetScreenshot();
image.SaveAsFile(path + ".png", ScreenshotImageFormat.Png);
ExtentReport.exChildTest.Log(status, stepDetail, MediaEntityBuilder.CreateScreenCaptureFromPath(path + ".png").Build());
}
public static void ReadJsonObject(string filename)
{
string myJsonString = File.ReadAllText(#"..\\..\\..\\" + filename);
jobject = JObject.Parse(myJsonString);
}
public static void ReadJsonArray(string filename)
{
string myJsonString = File.ReadAllText(#"..\\..\\..\\" + filename);
jarray = JArray.Parse(myJsonString);
}
I have this code here that saves bitmaps of images as a GIF file called test, but everytime the user saves it as test.gif so its constantly overwriting.
What are some ways to avoid overweriting and generate a new filename everytime programmatically?
if(imagesPathList !=null){
if(imagesPathList.size()>1) {
Toast.makeText(MainActivity.this, imagesPathList.size() + " no of images are selected", Toast.LENGTH_SHORT).show();
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/dir1/dir2");
dir.mkdirs();
File file = new File(dir, "test.gif");
try{
FileOutputStream f = new FileOutputStream(file);
f.write(generateGIF(list));
} catch(Exception e) {
e.printStackTrace();
}
A quick and dirty solution is to put the system time in the filename:
File file = new File(dir, "test_" + System.currentTimeMillis() +".gif");
As long as that method isn't executed at the exact same millisecond, you won't have duplicates.
You can use java.io.File.createTempFile("test", ".gif", dir)
This creates unique filename but they might get significantly long after some time.
Alternatively you can create a method that creates unique filesnames yourself:
private File createNewDestFile(File path, String prefix, String suffix) {
File ret = new File(path, prefix + suffix);
int counter = 0;
while (ret.exists()) {
counter++;
ret = new File(path, prefix + "_" + counter + suffix);
}
return ret;
}
Instead of
File file = new File(dir, "test.gif");
you call
File file = createNewDestFile(dir, "test", ".gif");
This is not thread safe. For that you need a more sophisticated method (e.g. synchronize it and create a FileOutputStream instead of a File which is creating the file already before another call checks of the method checks its existence).
The exif interface is used in my application to write new data to a stored image,captured using the camera intent in Android.
The problem is when the image file is output to storage, my code for updating the attributes of the image doesn't actually update the stored image when I view details of the image in the gallery.
For example I use the UserComment tag to add some generic text as a test input but this is not displayed in the image's details on the device.
My question is, how can I check if the data is actually being written to the file?
If I know that the attributes are being appended to the image then I can debug the storage of the file as the problem.
This is the getOutputPhotoFile() method which retrieves the last captured image in the directory of the project:
private File getOutputPhotoFile() throws IOException {
File directory = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), getPackageName());
if (!directory.exists()) {
if (!directory.mkdirs()) {
Log.e(TAG, "Failed to create storage directory.");
return null;
}
}
String timeStamp = new SimpleDateFormat("yyyMMdd_HHmmss", Locale.ENGLISH).format(new Date());
File[] files = directory.listFiles();
File origFile = new File(directory.getPath(), "IMG_" + timeStamp + ".jpg");
if(files.length!=0) {
File newestFile = files[files.length-1];
origFile = new File(directory.getPath() + File.separator + newestFile.getName());
}
String mString = "Generic Text..";
ExifInterface exifFile = new ExifInterface(origFile.getAbsolutePath());
exifFile.setAttribute("UserComment", mString);
exifFile.setAttribute(ExifInterface.TAG_GPS_LATITUDE,
String.valueOf(latituteField.toString()));
exifFile.setAttribute(ExifInterface.TAG_GPS_LONGITUDE,
String.valueOf(longitudeField.toString()));
exifFile.saveAttributes();
return origFile;
}
Upon looking into ExifInterface API, it seems that there is no Exif TAG with the name "UserComment".
It seems that it only supports TAGs mentioned in the given API.
After setting the location values, you can use same ExifInterface API getAttribute(ExifInterface.TAG_GPS_LATITUDE,) and getAttribute(ExifInterface.TAG_GPS_LONGITUDE) to check whether the file has the values set.
take an screenshot and copy that file in my local folder using java io (Webdriver with Java)
File screenshot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("d:\\pic\\report.jpg"));
i call this method more than one time, so in this situation i dont want to repeat the file name as "report.jpg" so please provide an suggestion how can i change that file name dynamically
like
report1
report2 etc.,
A very simple way:
FileUtils.copyFile(screenshot, new File("d:\\pic\\report_" + System.currentTimeMillis() + ".jpg");
I just hope you don't do a screenshot every milliseconds. ;-)
You can improve the readability by using a timestamp.
java.text.SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMDD'T'HHMMSSsss");
String newFileName = "d:\\pic\\report_" + sdf.format(new java.util.Date()) + ".jpg";
FileUtils.copyFile(screenshot, newFileName);
Another solution might be to use a static counter in an helper class.
private static int count = 0;
public static void doScreenshot() {
count++;
String newFileName = "d:\\pic\\report_" + count + ".jpg";
FileUtils.copyFile(screenshot, newFileName);
}
You could append the current date and time, or go in a loop checking if the file already exists, appending an number once the file is available.
Date and Time (more meaningful):
Date currDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
String dateAndTime = dateFormat.format(currDate);
File reportFile = new File("d:\\pic\\report_" + dateAndTime + ".jpg");
File screenshot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, reportFile));
Number increment method:
File reportFile;
int number = 0;
do {
reportFile = new File("d:\\pic\\report" + number + ".jpg");
number++;
} while (reportFile.exists());
File screenshot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, reportFile));
There are many options.
If the suffix number is important:
Save in a file or in DB the number of times you have generated it
Get the number that contains the name of the last generated file
Count the number of images in the folder (not valid it you delete them after a while)
If it is not important:
Use a datetime with the current time
Use a random number