java image upload using html5 error "Invalid argument to native writeImage" - java

I am trying to use html 5 image upload, but the problem I'm facing is when I try to decode the 64 encoded image it throws some error, here is my code:
public String decodeToImage() throws IOException {
destPath = "/home/user/deskTop";
byte[] imageByte;
String imageData = request.getParameter("img");
String base64Image = imageData.split(",")[1];
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(base64Image);
BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageByte));
File outputfile = new File(destPath, "11111.png");
try
{
ImageIO.write(img, "jpg", outputfile);
}
catch(Exception e)
{
e.printStackTrace();
}
return SUCCESS;
}
When I am trying to write the image in File from Buffer Image it throws this error:
"Invalid argument to native writeImage"
When I asked the error elsewhere, someone said that it may be because of using open-jdk.
Here is my JavaScriot:
crop = function() {
//Find the part of the image that is inside the crop box
var crop_canvas,
left = $('.imgOverlay').offset().left - $container.offset().left,
top = $('.imgOverlay').offset().top - $container.offset().top,
width = $('.imgOverlay').width(),
height = $('.imgOverlay').height();
crop_canvas = document.createElement('canvas');
crop_canvas.width = width;
crop_canvas.height = height;
crop_canvas.getContext('2d').drawImage(image_target, left, top, width, height, 0, 0, width, height);
var onSuccesOfUpload = function(data) {
alert();
};
var onErrorOfUpload = function(data) {
alert();
};
var data = function(data) {
alert();
};
var data = {
'img': crop_canvas.toDataURL("image/png")
};
callToDB('/canvasImageUpload.action', 'POST', data, onSuccesOfUpload, onErrorOfUpload);
}

Related

Xuggler recording in AVI format

Hi I am trying to use Xuggler for screen recording video in AVI format.but I am getting the following exception while doing the same.couldn't not open the stream.I changed the width and height as well but no use.
Exception in thread "main" java.lang.RuntimeException: could not open stream com.xuggle.xuggler.IStream#4088416[index:0;id:0;streamcoder:com.xuggle.xuggler.IStreamCoder#4088512[codec=com.xuggle.xuggler.ICodec#4088848[type=CODEC_TYPE_VIDEO;id=CODEC_ID_H264;name=libx264;];time base=1/1000000;frame rate=0/0;pixel type=YUV420P;width=683;height=384;];framerate:0/0;timebase:1/90000;direction:OUTBOUND;]: Operation not permitted
at com.xuggle.mediatool.MediaWriter.openStream(MediaWriter.java:1192)
at com.xuggle.mediatool.MediaWriter.getStream(MediaWriter.java:1052)
at com.xuggle.mediatool.MediaWriter.encodeVideo(MediaWriter.java:799)
at com.atmecs.ep.ScreenRecording.main(ScreenRecording.java:52)
public class ScreenRecording {
private static final double FRAME_RATE = 50;
private static final int SECONDS_TO_RUN_FOR = 30;
private static final String outputFilename = "c:/today.avi";
private static Dimension screenBounds;
public static void main(String[] args) {
// let's make a IMediaWriter to write the file.
final IMediaWriter writer = ToolFactory.makeWriter(outputFilename);
screenBounds = Toolkit.getDefaultToolkit().getScreenSize();
// We tell it we're going to add one video stream, with id 0,
// at position 0, and that it will have a fixed frame rate of
// FRAME_RATE.
writer.addListener(ToolFactory.makeDebugListener());
writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_H264, screenBounds.width / 2, screenBounds.height / 2);
long startTime = System.nanoTime();
for (int index = 0; index < SECONDS_TO_RUN_FOR * FRAME_RATE; index++) {
// take the screen shot
BufferedImage screen = getDesktopScreenshot();
// convert to the right image type
BufferedImage bgrScreen = convertToType(screen, BufferedImage.TYPE_3BYTE_BGR);
// encode the image to stream #0
writer.encodeVideo(0, bgrScreen, System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
// sleep for frame rate milliseconds
try {
Thread.sleep((long) (1000 / FRAME_RATE));
} catch (InterruptedException e) {
// ignore
}
}
// tell the writer to close and write the trailer if needed
writer.close();
}
public static BufferedImage convertToType(BufferedImage sourceImage, int targetType) {
BufferedImage image;
// if the source image is already the target type, return the source
// image
if (sourceImage.getType() == targetType) {
image = sourceImage;
}
// otherwise create a new image of the target type and draw the new
// image
else {
image = new BufferedImage(sourceImage.getWidth(), sourceImage.getHeight(), targetType);
image.getGraphics().drawImage(sourceImage, 0, 0, null);
}
return image;
}
private static BufferedImage getDesktopScreenshot() {
try {
Robot robot = new Robot();
Rectangle captureSize = new Rectangle(screenBounds);
return robot.createScreenCapture(captureSize);
} catch (AWTException e) {
e.printStackTrace();
return null;
}
}
}
can you give any suggestion for encoding the video(only AVI)

Android: Images are stored at the end of the gallery

can somebody help me with this problem?
I want that images are displayed at the beginning of the gallery.
What have i to change in my code?
OutputStream fOut = null;
try {
String path = getFilesDir().getPath();
File file = new File(path, "LT-IMG-"+ts+".jpg");
fOut = new FileOutputStream(file);
Bitmap bitmap = ((BitmapDrawable)photoView.getDrawable()).getBitmap();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
} catch (IOException ex) {
ex.printStackTrace();
}
MediaStore.Images.Media.insertImage(getContentResolver(), yourBitmap, yourTitle , yourDescription);
The former code will add the image at the end of the gallery. If you want to modify the date so it appears at the beginning or any other metadata, see the code below (Cortesy of S-K, samkirton):
https://gist.github.com/samkirton/0242ba81d7ca00b475b9
/**
* Android internals have been modified to store images in the media
folder with * the correct date meta data * #author samuelkirton*/
public class CapturePhotoUtils {
/**
* A copy of the Android internals insertImage method, this method populates the
* meta data with DATE_ADDED and DATE_TAKEN. This fixes a common problem where media
* that is inserted manually gets saved at the end of the gallery (because date is not populated).
* #see android.provider.MediaStore.Images.Media#insertImage(ContentResolver, Bitmap, String, String)
*/
public static final String insertImage(ContentResolver cr,
Bitmap source,
String title,
String description) {
ContentValues values = new ContentValues();
values.put(Images.Media.TITLE, title);
values.put(Images.Media.DISPLAY_NAME, title);
values.put(Images.Media.DESCRIPTION, description);
values.put(Images.Media.MIME_TYPE, "image/jpeg");
// Add the date meta data to ensure the image is added at the front of the gallery
values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());
Uri url = null;
String stringUrl = null; /* value to be returned */
try {
url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
if (source != null) {
OutputStream imageOut = cr.openOutputStream(url);
try {
source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);
} finally {
imageOut.close();
}
long id = ContentUris.parseId(url);
// Wait until MINI_KIND thumbnail is generated.
Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id, Images.Thumbnails.MINI_KIND, null);
// This is for backward compatibility.
storeThumbnail(cr, miniThumb, id, 50F, 50F,Images.Thumbnails.MICRO_KIND);
} else {
cr.delete(url, null, null);
url = null;
}
} catch (Exception e) {
if (url != null) {
cr.delete(url, null, null);
url = null;
}
}
if (url != null) {
stringUrl = url.toString();
}
return stringUrl;
}
/**
* A copy of the Android internals StoreThumbnail method, it used with the insertImage to
* populate the android.provider.MediaStore.Images.Media#insertImage with all the correct
* meta data. The StoreThumbnail method is private so it must be duplicated here.
* #see android.provider.MediaStore.Images.Media (StoreThumbnail private method)
*/
private static final Bitmap storeThumbnail(
ContentResolver cr,
Bitmap source,
long id,
float width,
float height,
int kind) {
// create the matrix to scale it
Matrix matrix = new Matrix();
float scaleX = width / source.getWidth();
float scaleY = height / source.getHeight();
matrix.setScale(scaleX, scaleY);
Bitmap thumb = Bitmap.createBitmap(source, 0, 0,
source.getWidth(),
source.getHeight(), matrix,
true
);
ContentValues values = new ContentValues(4);
values.put(Images.Thumbnails.KIND,kind);
values.put(Images.Thumbnails.IMAGE_ID,(int)id);
values.put(Images.Thumbnails.HEIGHT,thumb.getHeight());
values.put(Images.Thumbnails.WIDTH,thumb.getWidth());
Uri url = cr.insert(Images.Thumbnails.EXTERNAL_CONTENT_URI, values);
try {
OutputStream thumbOut = cr.openOutputStream(url);
thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut);
thumbOut.close();
return thumb;
} catch (FileNotFoundException ex) {
return null;
} catch (IOException ex) {
return null;
}
}
}

Android render pdf to bitmap with itext library

I am trying to convert a pdf stored in my assets folder into bitmap using PdfViewer.jar.
This is my code:
public static Bitmap renderToBitmap(InputStream inStream) {
Bitmap bitmap = null;
try {
byte[] bArray = IOUtils.toByteArray(inStream);
ByteBuffer buf = ByteBuffer.wrap(bArray);
PDFPage mPdfPage = new PDFFile(buf).getPage(0, true);
float width = mPdfPage.getWidth();
float height = mPdfPage.getHeight();
bitmap = mPdfPage.getImage((int) (width), (int) (height), null);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inStream.close();
} catch (IOException e) {
// do nothing because the stream has already been closed
}
}
return bitmap;
}
This code is doing what I need. But the resulting bitmap quality is very poor.
How can I increase the quality of bitmap created ?

How to create an image from first page of a pdf in iText

I want to create image from first page of an PDF . I am using iText in java . Can you suggest me what to do to extract first page of an pdf as an image ?
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(
document, new FileOutputStream(RESULT));
document.open();
File extStore = Environment.getExternalStorageDirectory();
String path=extStore.getPath()+"/FirstPdf.pdf";
PdfReader reader = new PdfReader(path);
int n = reader.getNumberOfPages();
PdfImportedPage page;
for (int i = 1; i <= n; i++) {
page = writer.getImportedPage(reader, i);
// Image.getInstance(page) ;
}
document.close();
I have written the above code . What to do to extract first page of a pdf as an image and save it in SDCARD ?
iText doesn't work for that purpose.
http://www.java2s.com/Open-Source/Android_Free_Code/Pdf/Download_Free_code_Android_Pdf_Viewer_Library.htm
The jar file is in the zip.
Download that library PdfViewer.jar and try this code:
byte[] bytes;
try {
File file = new File("/storage/extSdCard/Test.pdf");
FileInputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
ByteBuffer buffer = ByteBuffer.NEW(bytes);
String data = Base64.encodeToString(bytes, Base64.DEFAULT);
PDFFile pdf_file = new PDFFile(buffer);
PDFPage page = pdf_file.getPage(2, true);
RectF rect = new RectF(0, 0, (int) page.getBBox().width(),
(int) page.getBBox().height());
Bitmap image = page.getImage((int)rect.width(), (int)rect.height(), rect);
FileOutputStream os = new FileOutputStream("/storage/extSdCard/pdf.jpg");
image.compress(Bitmap.CompressFormat.JPEG, 80, os);
//((ImageView) findViewById(R.id.testView)).setImageBitmap(image);
} catch (Exception e) {
e.printStackTrace();
}
You can change the rect around to make it extract any part of the pdf you want etc too, pretty good. Spent about 16 hours banging my head against a wall before finding that solution. Wasn't really sure if it was possible without the swing awt library. Sorry the storage is hard coded but it was the least of my concerns at the time.
I ended up finding out how to do what the question initially asked!!!
You need iTextG library (itextg-5.5.3.jar), scpkix-jdk15on.1.47.0.1.jar & scprov-jdk15on-1.47.0.2.jar
inside where want to call it from:
public static final String RESULT = "/storage/sdcard0/dirAtExtStorage/Img%s.%s";
public void extractImages(String filename)
throws IOException, DocumentException {
PdfReader reader = new PdfReader(filename);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
MyImageRenderListener listener = new MyImageRenderListener(RESULT);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
parser.processContent(i, listener);
}
}
inside MyImageRendererListener.java:
public class MyImageRenderListener implements RenderListener{
private String path;
public MyImageRenderListener(String path) {
this.path = path;
}
#Override
public void beginTextBlock() {
// TODO Auto-generated method stub
}
#Override
public void endTextBlock() {
// TODO Auto-generated method stub
}
public void renderImage(ImageRenderInfo renderInfo) {
try {
System.out.print("renderImage");
String filename;
FileOutputStream os;
PdfImageObject image = renderInfo.getImage();
if (image == null) return;
filename = String.format(path, renderInfo.getRef().getNumber(), image.getFileType());
os = new FileOutputStream(filename);
os.write(image.getImageAsBytes());
os.flush();
os.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
#Override
public void renderText(TextRenderInfo arg0) {
// TODO Auto-generated method stub
}
}
enjoy guys

jpegs are corrupted when resampled with java imageIO

The JPEG Images that ImageIO generated view correctly on windows file explorer, as well as safari webbrowser, but in FireFox, the resampled images are clipped.
How do I use ImageIO without corrupting the resamples?
The code should resize image keeping aspect ratio, as well as do jpeg compression, the convert it to a byte [] array, which could be written to a socket.
some of my code. in this snippet, I tried adding Jui library, but still the same issue.
public static BufferedImage imageistream;
public void Resample(String child,double width,double height) throws Exception, InvalidFileStructureException, InvalidImageIndexException, UnsupportedTypeException, MissingParameterException, WrongParameterException
{
String imagePath = "";
if(this.is_mac_unix == true)
{
imagePath = this.path+"/"+child;
}
else
{
imagePath = this.path+"\\"+child;
}
PixelImage bmp = null;
try {
bmp = ToolkitLoader.loadViaToolkitOrCodecs(imagePath, true, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Resample resample = new Resample();
resample.setInputImage(bmp);
double fixedRatio = width/height;
if(((double)bmp.getWidth()/bmp.getHeight()) >= fixedRatio)
{
resample.setSize((int)width,(int)(bmp.getHeight()/(bmp.getWidth()/width)));
}
else
{
resample.setSize((int)width,(int)(bmp.getWidth()/(bmp.getHeight()/height)));
}
resample.setFilter(Resample.FILTER_TYPE_LANCZOS3);
resample.process();
PixelImage scaledImage = resample.getOutputImage();
Processor.imageistream = ImageCreator.convertToAwtBufferedImage(scaledImage);
bmp = null;
Runtime rt = Runtime.getRuntime();
rt.gc();
}
...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(Processor.imageistream, "jpg", baos);
// ImageIO.write(Processor.imageistream, "png", baos); Works!
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte bytes[] = baos.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
OutputStream os = (OutputStream)obj[1];
OutputStreamWriter writer = (OutputStreamWriter)obj[0];
byte[] buf= new byte[4096];
int c;
try {
while (true) {
c= is.read(buf);
if (c<= 0) break;
os.write(buf, 0, c);
}
writer.close();
os.close();
is.close();
I've been successfully using:
BufferedImage bufferedImage = ImageIO.read(..);
Image img = bufferedImage.getScaledInstance(..);
BufferedImage result = // transform Image to BufferedImage
ImageIO.write(result, "image/jpeg", response.getOutputStream());
transformation is simply writing the contents of the image to a new BufferedImage

Categories