How to set Content-Length in response header for Jfree chart? - httpresponse

I have a servlet which is creating the jfree chart. By default it is returning tranfer-encoding as chunked. But I have to set the Content-Length in the response header.
final JFreeChart chart = ChartController.createChart();
final int chartWidth = ChartUtils.calculateWidth(request);
final int chartHeight = ChartHelper.getQuickViewChartHeight();
final ServletOutputStream out = response.getOutputStream();
response.setContentType("image/png");
ChartUtilities.writeChartAsPNG(out, chart, chartWidth, chartHeight);

As suggested here, it's not meaningful to set the content-length header and also use chunked transfer encoding. In either case, as outlined here, you can use ChartUtilities.encode() to determine the byte length of the encoded image array:
byte[] b = ChartUtilities.encode(chart.createBufferedImage(chartWidth, chartHeight));
int imageLength = b.length;
Later, you can write() the encoded image to the output stream:
out.write(b);

Related

Why I am unable to change the QR Code's size in iText7?

How to change QR Code size?
using (iText.Kernel.Pdf.PdfReader _pdf_reader =
new iText.Kernel.Pdf.PdfReader("tmp/example.pdf"))
{
using (iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(_pdf_reader, new iText.Kernel.Pdf.PdfWriter("tmp/output.pdf").SetSmartMode(true)))
{
BarcodeQRCode qrc = new BarcodeQRCode("https://google.com");
PdfFormXObject xObject = qrc.CreateFormXObject(ColorConstants.BLACK, pdfDoc);
float _w = pdfDoc.GetPage(1).GetPageSize().GetWidth();
float _h = pdfDoc.GetPage(1).GetPageSize().GetHeight();
PdfCanvas canvas = new PdfCanvas(pdfDoc.GetPage(1));
canvas.SaveState();
canvas.SetFillColor(ColorConstants.LIGHT_GRAY);
//canvas.Rectangle(_w - 90, _h - 90, 100, 100);
canvas.Fill();
canvas.RestoreState();
canvas.AddXObject(xObject, _w - qrc.GetBarcodeSize().GetWidth(), _h - qrc.GetBarcodeSize().GetHeight());
}
}
I try:
qrc.GetBarcodeSize().GetHeight();
qrc.GetBarcodeSize().GetWidth();
it returns 33
I try to set Height & Width to 100 like below:
qrc.GetBarcodeSize().SetHeight(100);
qrc.GetBarcodeSize().SetWidth(100);
and then check the size again, but it keeps returning 33, is it a bug? or Did I miss something?
please help
thanks
Don
I try to set Height & Width to 100 like below:
Actually, you can`t change the QrCode side this way.
In fact, QRcode is an n*n grid where n depends on some parameters as a QR code version and the error correction level.
When generating, iText uses the smallest version that can fit the content. This is version 4 (33*33) in your case.
The easiest way to change the size of QrCode in a document is by using the version of the createFormXObject method which accepts the moduleSide parameter.
float moduleSize = 100/qrc.GetBarcodeSize().GetHeight();
qrc.createFormXObject(foreground, moduleSize, document)
Module size here is size of the barcode`s grid cell (1 by default).
iTxt 7 Qrcode size effected by three parameter in hints, example example for your reference.
//C# code
//Prepare all necessary properties to create the qrcode
IDictionary<EncodeHintType, Object> hints = new Dictionary<EncodeHintType, object>();
//default character set (ISO-8859-1)
hints[EncodeHintType.CHARACTER_SET] = "UTF-8";
//Qrcode Error correction level L,M,Q,H
//default ErrorCorrectionLevel.L
hints[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.L;
//Qrcode minimal version level
//default 4
hints[EncodeHintType.MIN_VERSION_NR] = 6;
string code = "Qrcode content here";
BarcodeQRCode qrcode = new BarcodeQRCode(code, hints);

Google CloudML serving_input_receiver_fn() b64 decode error

I am sending a base64 encoded image via AJAX POST to a model stored in Google CloudML. I am getting an error telling me that my input_fn(): is failing to decode the image and transform it into jpeg.
Error:
Prediction failed: Error during model execution:
AbortionError(code=StatusCode.INVALID_ARGUMENT,
details="Expected image (JPEG, PNG, or GIF), got
unknown format starting with 'u\253Z\212f\240{\370
\351z\006\332\261\356\270\377' [[{{node map/while
/DecodeJpeg}} = DecodeJpeg[_output_shapes=
[[?,?,3]], acceptable_fraction=1, channels=3,
dct_method="", fancy_upscaling=true, ratio=1,
try_recover_truncated=false,
_device="/job:localhost/replica:0 /task:0
/device:CPU:0"](map/while/TensorArrayReadV3)]]")
Below is the full Serving_input_receiver_fn():
The first step I believe is to handle the incoming b64 encoded string and decode it. This is done with:
image = tensorflow.io.decode_base64(image_str_tensor)
The next step I believe is to open the bytes, but this is where I dont know how to handle the decoded b64 string with tensorflow code and need help.
With a python Flask app this can be done with:
image = Image.open(io.BytesIO(decoded))
pass the bytes through to get decoded by tf.image.decode_jpeg ????
image = tensorflow.image.decode_jpeg(image_str_tensor, channels=CHANNELS)
Full input_fn(): code
def serving_input_receiver_fn():
def prepare_image(image_str_tensor):
image = tensorflow.io.decode_base64(image_str_tensor)
image = tensorflow.image.decode_jpeg(image_str_tensor, channels=CHANNELS)
image = tensorflow.expand_dims(image, 0) image = tensorflow.image.resize_bilinear(image, [HEIGHT, WIDTH], align_corners=False)
image = tensorflow.squeeze(image, axis=[0])
image = tensorflow.cast(image, dtype=tensorflow.uint8)
return image
How do I decode my b64 string back into jpeg and then convert the jpeg to a tensor?
This is a sample for processing b64 images.
HEIGHT = 224
WIDTH = 224
CHANNELS = 3
IMAGE_SHAPE = (HEIGHT, WIDTH)
version = 'v1'
def serving_input_receiver_fn():
def prepare_image(image_str_tensor):
image = tf.image.decode_jpeg(image_str_tensor, channels=CHANNELS)
return image_preprocessing(image)
input_ph = tf.placeholder(tf.string, shape=[None])
images_tensor = tf.map_fn(
prepare_image, input_ph, back_prop=False, dtype=tf.uint8)
images_tensor = tf.image.convert_image_dtype(images_tensor, dtype=tf.float32)
return tf.estimator.export.ServingInputReceiver(
{'input': images_tensor},
{'image_bytes': input_ph})
export_path = os.path.join('/tmp/models/json_b64', version)
if os.path.exists(export_path): # clean up old exports with this version
shutil.rmtree(export_path)
estimator.export_savedmodel(
export_path,
serving_input_receiver_fn=serving_input_receiver_fn)

How to convert Embedded image to Base64 string in xamarin forms..?

I want to convert an Embedded image to base 64 string. The image is in PCL solution so let me know how to convert an image into base64. As I tried lots of ways but I am not getting the file path properly. So please help me with this.
//file to base64 string
byte[] b = System.IO.File.ReadAllBytes(FileName);
String s = Convert.ToBase64String(b);
//base64 string to file
byte[] data = Convert.FromBase64String(s);
System.IO.File.WriteAllBytes(FileName2, data);
Since it is an embedded resource getting the path for the image is a problem to convert it into a stream, you can take the following steps to get the path of your embedded image:
string imagePath = "NameOfProject.Assets.applicationIcon.png";
Note: This is the sample path in your case you will give your path, Where the name of the project is the name of the project, Assets is the folder in which I have the image and application icon is the image. (I hope you understood what I am doing here)
After that get the Assembly details something like this:
Assembly assembly = typeof(NameOfClass).GetTypeInfo().Assembly;
Then inside a using statement convert your image into a stream, Something like this
string result;
using (Stream stream = assembly.GetManifestResourceStream(imagePath))
{
long length = stream.Length;
byte[] buffer = new byte[length];
stream.Read(buffer, 0, (int)length);
result = Convert.ToBase64String(data);
}
Revert in case of queries.

How to detect numbers/digits via builtin OcrEngine class

I have troubles detecting digits/numbers in an image with the Windows UWP OCR-Engine from C++/CX.
I need to detect the number in the following Image
I tried it by using the builtin method for Windows 10 UWP: OcrEngine with the following code:
...
cv::Mat croppedImage = imread("digit.png");
WriteableBitmap^ bit1 = ref new WriteableBitmap(croppedImage.cols, croppedImage.rows);
SoftwareBitmap^ bit2 = bit2->CreateCopyFromBuffer(bit1->PixelBuffer, BitmapPixelFormat::Bgra8, bit1->PixelWidth, bit1->PixelHeight);
Windows::Globalization::Language^ l = ref new Windows::Globalization::Language("de");
OcrEngine^ ocrEngine = OcrEngine::TryCreateFromLanguage(l);
IAsyncOperation<OcrResult^>^ ao = ocrEngine->RecognizeAsync(bit2);
task_completion_event<Platform::String^> purchaseCompleted;
auto deviceEnumTask = create_task(ao);
deviceEnumTask.then([this](OcrResult^ result)
{
App1::MainPage::findNumber(result->Text);
});
...
void App1::MainPage::findNumber(Platform::String^ text)
{
//Do something with String
}
My Problem is now, that the inserted string in findNumber is always null. I tried with different pictures as input but always the same result: NULL.
Is there an easier way to get the digits in this images in C++/CX?
What could be the problem? Converting the image?
The problem was the conversion of the WriteableBitmap to a SoftwareBitmap WriteableBitmap^ bit1 = ref new WriteableBitmap(croppedImage.cols, croppedImage.rows);
// Get access to the pixels
IBuffer^ buffer = bit1->PixelBuffer;
unsigned char* dstPixels;
// Obtain IBufferByteAccess
ComPtr<IBufferByteAccess> pBufferByteAccess;
ComPtr<IInspectable> pBuffer((IInspectable*)buffer);
pBuffer.As(&pBufferByteAccess);
// Get pointer to pixel bytes
pBufferByteAccess->Buffer(&dstPixels);
memcpy(dstPixels, croppedImage.data, croppedImage.step.buf[1] * croppedImage.cols*croppedImage.rows);
SoftwareBitmap^ bit2= ref new SoftwareBitmap(BitmapPixelFormat::Bgra8, croppedImage.cols, croppedImage.rows);
//SoftwareBitmap^ bit2 =
bit2->CopyFromBuffer(bit1->PixelBuffer);

Parse PDF with ABCPDF

I want to parse a PDF document I download with ABCPDF, but I cant find any elements in the document or how to reach them and iterate them. I want to parse out some text.
var webClient = new WebClient();
var bytes = webClient.DownloadData("http://test.com/test.pdf");
var doc = new Doc();
doc.Read(bytes);
Use the Doc.GetText method to extract content from the current page, specifying the format in which content is to be returned.
doc.PageNumber = 1;
string pageContent = doc.GetText("Text");
The example above will return plain text in layout order. Specifying "SVG" or "SVG+" returns additional information along with the text, such as style and position.

Resources