Base64String in Windows 8 - windows

I've got a windows 8 program that uses an image picker and downloads the selected image on the server.
The server provides an API which needs the image to be converted in base64string. And an image must be less than 7Mb.
I'm using the code below:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
// Application now has read/write access to the picked file
bitmap = new BitmapImage();
byte[] buf;
using (var stream = await file.OpenStreamForReadAsync())
{
buf = ReadToEnd(stream);
}
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{
base64String = Convert.ToBase64String(buf);
bitmap.SetSource(stream);
}
}
And the bitmap goes to the server.
But there is a problem: the bitmap size is much more bigger than jpg's size, for example. And none of small jpgs go to the server, because their bitmap version is larger than 7 Mb.
Can I convert an image to base64string without converting it to a bitmap?

In this code, you read the image (encoded in jpeg) and convert it to a base 64 string.
You can not reduce the size of the base 64 without reducing the size of the image.
To do so, you can use a BitmapEncoder/Decoder and resize the image to a smaller size.
Regards

Related

How to use Itext to add an image file into an existing PDF, and declare a unique name for it?

In order to find an added image file and replace it with another image file when I read a PDF next time, I want to use Itext to add an image file into an existing PDF, and declare a unique name for it.
My code:
final PdfName key = new PdfName("MY_SIGN_KEY");
final PdfName val = new PdfName("MY_SIGN_VAL");
Image signImage=Image.getInstance(signPngFile.getAbsolutePath());
signImage.setAlignment(1);
signImage.scaleAbsolute(newWidth, newHeight);
signImage.setAbsolutePosition(200,200);
PdfContentByte over = stamper.getOverContent(1);
PdfImage stream = new PdfImage(signImage, "", null);
stream.put(key,val);// a unique name for it.(设置唯一标识符)
//PdfIndirectObject ref=over.getPdfWriter().addToBody(stream);
//signImage.setDirectReference(ref.getIndirectReference());
over.addImage(signImage);
I have tried your code and it works for me. See the AddImageWithID example:
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
Image image = Image.getInstance(IMG);
PdfImage stream = new PdfImage(image, "", null);
stream.put(new PdfName("ITXT_SpecialId"), new PdfName("123456789"));
PdfIndirectObject ref = stamper.getWriter().addToBody(stream);
image.setDirectReference(ref.getIndirectReference());
image.setAbsolutePosition(36, 400);
PdfContentByte over = stamper.getOverContent(1);
over.addImage(image);
stamper.close();
reader.close();
}
In this example, I take a file named hello.pdf and I add an image named bruno.jpg with the file hello_with_image_id.pdf as result.
The image doesn't look black:
The ID is added:
Can you try the code I shared and see if the problem persists.
I can think of one reason why you'd get a black image: in our code, we assume that a single image is added. In the case of JPEG, this is always the case. In the case of PNG or GIF though, adding one source image could result in two images being added. Strictly speaking, PDF doesn't support transparent images (depending on how you interpret the concept of transparent images). Whenever you add a single source image with transparent parts, two images will be added to the PDF: one opaque image and one image mask. The combination of the opaque image and the image mask results in something that is perceived as a transparent image. Maybe this is what happens in your case.

load a thumbnail on QListWidget with reduced resolution

I need to reduce the resolution of the images that I add and show in a QListWidgtet.
Now I use the next code but it does not show all the images because they are being loaded with full resolution
void ImagesWizard::on_pbAddImages_clicked()
{
QFileDialog dialog(this);
dialog.setDirectory(mInitPath);
dialog.setFileMode(QFileDialog::ExistingFiles);
dialog.setNameFilter(trUtf8("Images (*.jpg *.png *.tif *.tiff *.bmp);; JPG (*.jpg);; PNG (*.png);; TIF (*.tif *.tiff);; BMP (*.bmp);;"));
QStringList filesToLoad;
if (dialog.exec())
filesToLoad = dialog.selectedFiles();
if (filesToLoad.count()!=0) {
QListWidget *localPathList= new QListWidget();
localPathList->setViewMode(QListWidget::IconMode );
localPathList->setIconSize(QSize(100,100));
localPathList->setResizeMode(QListWidget::Adjust);
localPathList->setSelectionMode(QAbstractItemView::MultiSelection);
for (int var = 0; var < filesToLoad.count(); ++var) {
if (!mImagesList->contains(filesToLoad[var])) {
QFileInfo fileInfo(filesToLoad[var]);
QString filename(fileInfo.fileName());
QListWidgetItem *listItem = new QListWidgetItem(QIcon(filesToLoad[var]),filename);
localPathList->addItem(listItem);
mImagesList->append(filesToLoad[var]);
}
}
pbNext->setFocus();
}
}
Is there any way to resize the resolution in of the QIcon to optimice the time consumed to load the images and to show all the images added?
Now if I load a lot of images the last QListWidgetItems only add the name.
Thanks for your help
Use QImage first to scale the image and construct the icon from the resulting pixmap.
QSize desiredSize;
Qimage orig(filesToLoad[var]);
Qimage scaled = orig.scaled(
desiredSize,
Qt::IgnoreAspectRatio,
Qt::SmoothTransformation);
QListWidgetItem *listItem = new QListWidgetItem(QIcon(Qpixmap::fromImage(scaled)),filename);
It is very common to store the presized image too on the disk, to avoid the two step conversion process.

pdfbox - rotation issue

As part of a project I am realizing, there are given pdfdocuments which include forms as JPEG Images within A4 pages inside this documents. If have to extract those JPGs out of the PDF. Later on those JPGs are used to build PDF Documents again.
When I simply open up those Documents with any PDFViewer they seem to have no rotation at all, at least it is not visible. So like this icon the have vertical format.
but when I use this sample code to extract the images :
PDDocument doc = PDDocument.load("/path/to/file);
List pages = doc.getDocumentCatalog().getAllPages();
Iterator iter = pages.iterator();
int i = 0;
while (iter.hasNext()) {
PDPage page = (PDPage) iter.next();
System.out.println(page.getRotation());
System.out.println("ROTATION = " + page.getRotation());;
PDResources resources = page.getResources();
Map pageImages = resources.getXObjects();
if (pageImages != null) {
Iterator imageIter = pageImages.keySet().iterator();
while (imageIter.hasNext()) {
String key = (String) imageIter.next();
if(((PDXObjectImage) pageImages.get(key)) instanceof PDXObjectImage){
PDXObjectImage image = (PDXObjectImage) pageImages.get(key);
image.write2file("/path/to/file" + i);
}
i ++;
}
}
}
all extracted JPGs are horizontal format. Further the sysout on the page.rotation tells me that the rotation is set to 270°.
How is that possible? 270 is set, but the PDF is shown vertical (I am no expert on PDF). I even did page.setRotate(0) before extracting the JPGs, but the images still remain horizontally. I read the following Thread telling how to rotate images before drawing them on the pdf. But i need to rotate them before writing them on the filesystem. What is the best way to achieve that?
Unfortunately, I can not attach any of the documents since they are confidential.

Get Images from media library in sequence

I am building app for windows phone 7 ,where i am taking screenshot in every 1 sec and all screenshot's are saving in media library and files name are 1.jpg,2.jpg,3.jpg.........etc. now when i am taking images from library i am getting images randomly like (1.jpg,2.jpg,3.jpg,7.jpg,13.jpg,4.jpg,15.jpg,5.jpg) not in sequence.
how can i get all images in sequence.here is my code
using (MediaLibrary mediaLibrary = new MediaLibrary())
{
PictureCollection AllScreenShot = mediaLibrary.Pictures;
foreach (Picture picture in AllScreenShot)
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!storage.DirectoryExists("SavedImg"))
storage.CreateDirectory("SavedImg");
if (storage.FileExists("SavedImg" + "\\" + picture.Name))
storage.DeleteFile("SavedImg" + "\\" + picture.Name);
using (IsolatedStorageFileStream file = storage.CreateFile("SavedImg" + "\\" + picture.Name))
picture.GetImage().CopyTo(file);
}
}
}
Create a list of Images and store all images in a list. It would be like this,
List<Image> listImage = new List<Image>(10); // say 10
listImage.Add(your image Item) in your case its pic 1.jpg; // cast before adding
List<Image> orderedList = listImage.OrderBy(k => k.ToString()).ToList();
Actually its not .ToString(). I declared to make you clear with the concept. In case of Image, you first need to convert it to byte[] and then store the byte[] in list and finally perform OrderBy option which will Order the images in sequence.

How to resize the image to be uploaded in JSP to a fix resolution?

I am uploading images for my site , I want every image uploaded to the server be of constant size.
So, when I display them from server to my site they can be uploaded quickly and the images use less server space.
code I am using to upload image using JSP.
logo_name = System.currentTimeMillis() + ".png";
File uploadedFile = new File("/www/static.appcanvas.com/"+logo_name);
item.write(uploadedFile);
Any related articles , some hints will be of great help
You didn't show us how you are parsing the upload. But, if "item is a org.apache.commons.fileupload.FileItem then you could use something lik the following.
BufferedImage bi = ImageIO.read(item.getInputStream());
Image img = bi.getScaledInstance(100,100,Image.SCALE_SMOOTH);
int w = img.getWidth();
int h = img.getHeight();
BufferedImage scaled = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g = scaled.createGraphics();
g.drawImage(img,0,0,null);
if(g != null) g.dispose();
ImageIO.write(scaled,"png", uploadedFile);

Resources