My test case is very simple: I'm generating a data matrix code and then I want to read it again. Both with xzing vs3.0.0. I'm doing this the same way with qr-code and pdf417 - and it works perfectly.
This is my code:
#Test
public void testDataMatrix() throws Exception {
writeDataMatrix();
String result = readDataMatrix("out/data_matrix.png", "UTF-8", new EnumMap<DecodeHintType, Object>(DecodeHintType.class));
assertEquals("my message", result);
}
public static void writeDataMatrix() throws IOException {
DataMatrixWriter writer = new DataMatrixWriter();
BitMatrix matrix = writer.encode("my message", BarcodeFormat.DATA_MATRIX, 100, 100);
MatrixToImageWriter.writeToPath(matrix, "PNG", Paths.get("out/data_matrix.png"));
}
public static String readDataMatrix(String filePath, String charset, Map hintMap)
throws FileNotFoundException, IOException, NotFoundException {
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(
new BufferedImageLuminanceSource(
ImageIO.read(new FileInputStream(filePath)))));
Result qrCodeResult = new MultiFormatReader().decode(binaryBitmap,
hintMap);
return qrCodeResult.getText();
}
If I run the test above, a data matrix image will be generated in out. This file is readable by the xzing online reader. But it works not in my own code:
com.google.zxing.NotFoundException
Any ideas? Thanks in advance.
I had the same problem but this worked for me. I think by default the library expects margins in the barcode so if you don't have them use the PURE_BARCODE hint.
public static String readDataMatrix(String filePath, String charset)
throws FileNotFoundException, IOException, NotFoundException
{
HashMap<DecodeHintType, Object> decodeHintMap = new HashMap<DecodeHintType, Object>();
decodeHintMap.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filePath)))));
Result codeResult = new DataMatrixReader().decode(binaryBitmap, decodeHintMap);
return codeResult.getText();
}
Related
Here is the code to read a PDF with iText5, and it works :
public class CreateTOC {
public static final String SRC = "file.pdf";
class FontRenderFilter extends RenderFilter {
public boolean allowText(TextRenderInfo renderInfo) {
String font = renderInfo.getFont().getPostscriptFontName();
return font.endsWith("Bold") || font.endsWith("Oblique");
}
}
public static void main(String[] args) throws IOException, DocumentException {
new CreateTOC().parse(SRC);
}
public void parse(String filename) throws IOException {
PdfReader reader = new PdfReader(filename);
Rectangle rect = new Rectangle(1000, 1000);
RenderFilter regionFilter = new RegionTextRenderFilter(rect);
FontRenderFilter fontFilter = new FontRenderFilter();
TextExtractionStrategy strategy = new FilteredTextRenderListener(
new LocationTextExtractionStrategy(), regionFilter, fontFilter);
System.out.println(PdfTextExtractor.getTextFromPage(reader, 56, strategy));
reader.close();
}
}
Can someone help me to do it working in iText7 ? There are problems with the Rectangle and the TextExtractionStrategy (it's not the same constructor as iText5)
Edit : RenderFilter isn't available in iText7...
I would like to use CognitiveJ (GitHub from CognitiveJ) but all I get is:
Status:401; Body: {"error":{"code":"Unspecified","message":"Access denied due to invalid subscription key. Make sure you are subscribed to an API you are trying to call and provide the right key."}}
Here is the Code:
public static String lic1 = "xxx";
public static String lic2 = "xxx";
public static void main(String[] args) throws IOException {
new Bildkontrolle();
}
public Bildkontrolle() throws IOException {
File imageFile = new File("E:\\DSC00306.jpg");
new FaceRecognicion(lic1, lic2, imageFile);
}
And here the second class:
public FaceRecognicion(String lic1, String lic2, File imageFile) throws IOException {
BufferedImage bufImage = ImageIO.read(imageFile);
InputStream inpStream = new FileInputStream(imageFile);
FaceScenarios faceScenarios = new FaceScenarios(lic1,
lic1);
ImageOverlayBuilder imageOverlayBuilder = ImageOverlayBuilder.builder(bufImage);
imageOverlayBuilder.outlineFacesOnImage(faceScenarios.findFaces(inpStream), RectangleType.FULL,
CognitiveJColourPalette.STRAWBERRY).launchViewer();
}
Does anyone have an examplecode where I can look up how to use the API.
I stuck at the point where to send the Request.
I want to convert a raster file into a shapefile. I am creating a GridCoverage2D object and want to use the execute method of Geotools PolygonExtractionProcess class but this method is not executing. I sadly cannot find any useful example usages of this class. This is my code:
try {
File rasterFile = new File("C:\\Data\\mytif.tif");
AbstractGridFormat format = GridFormatFinder.findFormat(rasterFile);
Hints hints = new Hints();
if (format instanceof GeoTiffFormat) {
hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
}
reader = format.getReader(rasterFile, hints);
GridCoverage2D coverage = reader.read(null); // It all works until this point
final PolygonExtractionProcess process = new PolygonExtractionProcess();
//System.out.println("This gets printed");
SimpleFeatureCollection sfColl = process.execute(coverage, null, Boolean.TRUE, null, null, null, null);
//System.out.println("This does not get printed anymore");
Style style = SLD.createPolygonStyle(Color.RED, null, 0.0f);
Layer layer = new FeatureLayer(sfColl, style);
map.addLayer(layer);
} catch (Exception e) {
System.err.println(e);
}
First, if all you want to do is extract vectors from a raster you could probably save using the process API completely by looking inside PolygonExtractionProcess to see how it works using the JAI.
But if you want to run a process then you should read the process tutorial which describes how they work and how to call them from your own code (this is usually used for testing). Essentially, the issue you are having comes from not understanding that processes are called from the processing engine (ProcessExecutor) which manages the input and output, and threading etc for you.
So your code should look something like this:
public class RasterToVector {
public static void main(String[] args)
throws IllegalArgumentException, IOException, InterruptedException, ExecutionException {
RasterToVector rtv = new RasterToVector();
SimpleFeatureCollection features = rtv.extract(args[0]);
Style style = SLD.createPolygonStyle(Color.RED, null, 0.0f);
Layer layer = new FeatureLayer(features, style);
MapContent map = new MapContent();
map.addLayer(layer);
JMapFrame.showMap(map);
}
org.geotools.process.Process process;
public RasterToVector() {
Name name = new NameImpl("ras", "PolygonExtraction");
process = Processors.createProcess(name);
}
private SimpleFeatureCollection extract(String filename)
throws IllegalArgumentException, IOException, InterruptedException, ExecutionException {
File rasterFile = new File(filename);
AbstractGridFormat format = GridFormatFinder.findFormat(rasterFile);
Hints hints = new Hints();
if (format instanceof GeoTiffFormat) {
hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE);
}
AbstractGridCoverage2DReader reader = format.getReader(rasterFile, hints);
GridCoverage2D coverage = reader.read(null);
ProcessExecutor engine = Processors.newProcessExecutor(2);
Map<String, Object> input = new KVP("data", coverage);
Progress working = engine.submit(process, input);
Map<String, Object> result = working.get();
SimpleFeatureCollection features = (SimpleFeatureCollection) result.get("result");
return features;
}
}
For a local terrain file I get the following result:
I am referring below Github link,
https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/storage/json-api/src/main/java/StorageSample.java
Code Snippet
public static void uploadFile(String bucketName, String targetPath, String filePath) throws Exception {
Storage storage = getStorage();
StorageObject object = new StorageObject();
object.setBucket(bucketName);
File file = new File(filePath);
InputStream stream = new FileInputStream(file);
try {
// String contentType =
// URLConnection.guessContentTypeFromStream(stream);
InputStreamContent content = new InputStreamContent("image/jpeg", stream);
Storage.Objects.Insert insert = storage.objects().insert(bucketName, null, content);
insert.setName(targetPath + file.getName());
insert.execute();
} finally {
stream.close();
}
}
public static void uploadFile(String name, String targetPath, String contentType, File file, String bucketName)
throws IOException, GeneralSecurityException, Exception {
InputStreamContent contentStream = new InputStreamContent(contentType, new FileInputStream(file));
contentStream.setLength(file.length());
StorageObject objectMetadata = new StorageObject().setName(targetPath + name)
.setAcl(Arrays.asList(new ObjectAccessControl().setEntity("allUsers").setRole("READER")));
Storage client = getStorage();
Storage.Objects.Insert insertRequest = client.objects().insert(bucketName, objectMetadata, contentStream);
insertRequest.execute();
}
private static Storage getStorage() throws Exception {
if (storage == null) {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
List<String> scopes = new ArrayList<String>();
scopes.add(StorageScopes.DEVSTORAGE_FULL_CONTROL);
// Collection<String> scopes = StorageScopes.all();
Credential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(jsonFactory).setServiceAccountId(getProperties().getProperty(ACCOUNT_ID_PROPERTY))
.setServiceAccountPrivateKeyFromP12File(
new File(getProperties().getProperty(PRIVATE_KEY_PATH_PROPERTY)))
.setServiceAccountScopes(scopes).build();
storage = new Storage.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(getProperties().getProperty(APPLICATION_NAME_PROPERTY)).build();
}
return storage;
}
public static void main(String[] args) throws Exception {
// CloudStorage.createBucket("my-bucket3/good");
CloudStorage.uploadFile("my-static", "temp/",
"/Users/rupanjan/Downloads/15676285_10158033346085311_1317913818452680683_o.jpg");
CloudStorage.uploadFile("15676285_10158033346085311_1317913818452680683_o.jpg", "temp/", "image/jpeg",
new File("/Users/rupanjan/Downloads/15676285_10158033346085311_1317913818452680683_o.jpg"),
"my-static");
// CloudStorage.downloadFile("my-bucket", "some-file.jpg",
// "/var/downloads");
List<String> buckets = CloudStorage.listBuckets();
System.out.println(buckets.size());
}
The issue I am facing,
I am able to upload the file successfully, but whenever, I click on that "Public Link", it downloads automatically. My intention was to share it for all user with read access.
N.B. If I am uploading the file manually from browser, I am able to open the file in browser, but when I upload it programically, it downloads everytime I click on "Public Link"
Please correct me if I am missing anything!!
It sounds like you know the name of the bucket and the object, and that the objects are all publicly readable, and that you want a URL that you can share that will allow others to read the object.
There is no need to use the "public link" functionality in the console for this. Public URLs can be constructed programmatically. They follow this pattern:
https://storage.googleapis.com/bucket_name/object_name
This question is based on this question.
With provided comments, i had written three different tests to validate properly set content-types.
#Test
public void testGetImageJpg_ShouldSucceed() throws Exception {
File testImage = new File(TestConstants.TEST_IMAGE_JPG);
byte[] expectedBytes = IOUtils.toByteArray(new FileInputStream(testImage));
when(service.getImage(anyString(), anyString())).thenReturn(testImage);
mockMvc.perform(get("/getImage/id/bla.jpg").sessionAttrs(session))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.IMAGE_JPEG))
.andExpect(content().bytes(expectedBytes));
}
#Test
public void testGetImagePng_ShouldSucceed() throws Exception {
File testImage = new File(TestConstants.TEST_IMAGE_PNG);
byte[] expectedBytes = IOUtils.toByteArray(new FileInputStream(testImage));
when(service.getImage(anyString(), anyString())).thenReturn(testImage);
mockMvc.perform(get("/getImage/id/bla.png").sessionAttrs(session))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.IMAGE_PNG))
.andExpect(content().bytes(expectedBytes));
}
#Test
public void testGetImageGif_ShouldSucceed() throws Exception {
File testImage = new File(TestConstants.TEST_IMAGE_GIF);
byte[] expectedBytes = IOUtils.toByteArray(new FileInputStream(testImage));
when(service.getImage(anyString(), anyString())).thenReturn(testImage);
mockMvc.perform(get("/getImage/id/bla.gif").sessionAttrs(session))
.andExpect(status().isOk()).andExpect(content().contentType(MediaType.IMAGE_GIF))
.andExpect(content().bytes(expectedBytes));
}
This is my controller, where all tests succeed:
#RequestMapping(value="/getImage/{id}/{path}", produces = {"image/png","image/jpeg","image/gif"})
#ResponseBody
byte[] getImage(#PathVariable("id") String id,
#PathVariable("path") String path) throws ImageNotFoundException {
File imageFile = service.getImage(id, path);
InputStream in;
try {
in = new FileInputStream(imageFile);
return IOUtils.toByteArray(in);
} catch (IOException e) {
throw new ImageNotFoundException();
}
}
But when I change the order of produces value to
produces = {"image/jpeg","image/png","image/gif"}
The test for png is failing:
java.lang.AssertionError: Content type expected:<image/png> but was:<image/jpeg>
Im little confused, that changing the order of produces values leads to different results.
Does anyone observed this, is it a bug or did I miss something ?