how to extract image from pdf using mupdf? - visual-c++

I want to extract image from pdf and save the image handle to std::vector,some time the background is incorrect,my code is follow.
BOOL CTextEditorDoc::loadImage()
{
if(m_strPDFPath.IsEmpty())
return FALSE;
CString strFile;
fz_context *ctx;
fz_document* doc;
fz_device *dev;
fz_irect bbox;
fz_rect bounds;
fz_matrix ctm;
fz_pixmap *image;
fz_colorspace *colorspace;
int i,j,rotation = 0;
int pagecount = 0;
fz_page *page;
BITMAPINFO bmi;
HBITMAP hBitmap;
LPBYTE pDest,pImage;
if(!gb2312toutf8(m_strPDFPath,strFile))
return FALSE;
ctx = fz_new_context(NULL, NULL, FZ_STORE_UNLIMITED);
fz_try(ctx){
doc = fz_open_document(ctx,strFile.GetBuffer(0));
}fz_catch(ctx){
fz_free_context(ctx);
return FALSE;
}
fz_rotate(&ctm, rotation);
colorspace = fz_device_rgb(ctx);
pagecount = fz_count_pages(doc);
pDest = NULL;
::ZeroMemory(&bmi, sizeof(BITMAPINFO));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biCompression = BI_RGB;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biWidth = 180;
bmi.bmiHeader.biHeight = -180;
bmi.bmiHeader.biSizeImage = 180*180*4;
for(i=0;i<pagecount;i++){
page = fz_load_page(doc,i);
if(i == 0){
fz_bound_page(doc,page,&bounds);
fz_pre_scale(&ctm,180/(bounds.x1 - bounds.x0),180/(bounds.y1 - bounds.y0));
fz_transform_rect(&bounds, &ctm);
fz_round_rect(&bbox, &bounds);
}
image = fz_new_pixmap_with_bbox(ctx,colorspace,&bbox);
dev = fz_new_draw_device(ctx,image);
fz_try(ctx){
fz_run_page(doc,page,dev,&ctm,NULL);
}fz_catch(ctx){
fz_drop_pixmap(ctx,image);
fz_free_device(dev);
fz_free_page(doc, page);
continue;
}
pImage = image->samples;
if(pImage){
pDest = NULL;
hBitmap = ::CreateDIBSection(NULL,&bmi,DIB_RGB_COLORS,(void**)&pDest,NULL,0);
ASSERT(hBitmap);
if(image->n == 2){ //not pallet
for (j = 180* 180; j > 0 ; j--){
pDest[0] = pDest[1] = pDest[2] = *pImage++;
pDest[3] = *pImage++;
pDest += 4;
}
}else if(image->n == 4){
//memcpy(pDest,pImage,m_thumbWidth * m_thumbHeight*4);
for (j = 180* 180; j > 0 ; j--){
pDest[0] = *pImage++;
pDest[1] = *pImage++;
pDest[2] = *pImage++;
pDest[3] = *pImage++;
pDest += 4;
}
}else ASSERT(FALSE);
m_imageVector.push_back(hBitmap);// save it to std::vector
}
fz_drop_pixmap(ctx,image);
fz_free_device(dev);
fz_free_page(doc, page);
}
fz_close_document(doc);
fz_free_context(ctx);
return TRUE;
}
this code can extract all the image of pdf but it maybe too slow ,how to improve it ?
some time the image's background is incorrect?
left of the follow picture is incorrect,right of the follow picture is real.

Like in the example of http://mupdf.com/docs/example.c
you forgot
fz_clear_pixmap_with_value(ctx, pix, 0xff);
to white the pixmap

Related

How to detect window state in linux?

I need to find out if a native linux application window is maximized or minimized in a java program.
I tried using X11.XGetWindowProperty() and I get some results also, but I cant make out any useful information in it.
I am using JNA 4.2.1, Java 8 update72 on Ubuntu 14.04 LTS. Any pointers will be very helpful. Thanks in advance to all.
[Edit]
I have the code below which gives me the result I need. But the result is not same for every invocation. The atoms which are returned for the window vary within invocations. Is there any other reliable way to get the window state?
private static X11 x11 = X11.INSTANCE;
private static Display dispy = x11.XOpenDisplay(null);
public static void main(String[] args) {
try {
X11.Atom[] atoms = getAtomProperties(
bytesToInt(getProperty(X11.XA_ATOM, X11.INSTANCE.XInternAtom(dispy, "_NET_WM_STATE", false))));
boolean hidden = false;
boolean vmax = false;
boolean hmax = false;
for (int i = 0; i < atoms.length; i++) {
X11.Atom atom = atoms[i];
if (atom == null)
continue;
String atomName = X11.INSTANCE.XGetAtomName(dispy, atom);
if ("_NET_WM_STATE_HIDDEN".equals(atomName)) {
hidden = true;
} else if ("_NET_WM_STATE_MAXIMIZED_VERT".equals(atomName)) {
vmax = true;
} else if ("_NET_WM_STATE_MAXIMIZED_HORZ".equals(atomName)) {
hmax = true;
}
}
if (hidden)
System.out.println("Window minimized");
else if (vmax && hmax && !hidden)
System.out.println("Window maximized");
else
System.out.println("Window normal");
} catch (X11Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static X11.Atom[] getAtomProperties(int[] ids) {
X11.Atom[] atoms = new X11.Atom[ids.length];
for (int i = 0; i < ids.length; i++) {
if (ids[i] == 0)
continue;
atoms[i] = new X11.Atom(ids[i]);
}
return atoms;
}
private static int[] bytesToInt(byte[] prop) {
if (prop == null)
return null;
int[] res = new int[prop.length / 4];
for (int i = 0; i < res.length; i++) {
res[i] = ((prop[i * 4 + 3] & 0xff) << 24) | ((prop[i * 4 + 2] & 0xff) << 16) | ((prop[i * 4 + 1] & 0xff) << 8)
| ((prop[i * 4 + 0] & 0xff));
if (res[i] != 0)
continue;
}
return res;
}
private static byte[] getProperty(X11.Atom xa_prop_type, X11.Atom xa_prop_name) throws X11Exception {
X11.Window window = new X11.Window(73400355);
X11.AtomByReference xa_ret_type_ref = new X11.AtomByReference();
IntByReference ret_format_ref = new IntByReference();
NativeLongByReference ret_nitems_ref = new NativeLongByReference();
NativeLongByReference ret_bytes_after_ref = new NativeLongByReference();
PointerByReference ret_prop_ref = new PointerByReference();
NativeLong long_offset = new NativeLong(0);
NativeLong long_length = new NativeLong(4096 / 4);
/*
* MAX_PROPERTY_VALUE_LEN / 4 explanation (XGetWindowProperty manpage):
*
* long_length = Specifies the length in 32-bit multiples of the data to be retrieved.
*/
if (x11.XGetWindowProperty(dispy, window, xa_prop_name, long_offset, long_length, false, xa_prop_type, xa_ret_type_ref,
ret_format_ref, ret_nitems_ref, ret_bytes_after_ref, ret_prop_ref) != X11.Success) {
String prop_name = x11.XGetAtomName(dispy, xa_prop_name);
throw new X11Exception("Cannot get " + prop_name + " property.");
}
X11.Atom xa_ret_type = xa_ret_type_ref.getValue();
Pointer ret_prop = ret_prop_ref.getValue();
if (xa_ret_type == null) {
// the specified property does not exist for the specified window
return null;
}
if (xa_ret_type == null || xa_prop_type == null || !xa_ret_type.toNative().equals(xa_prop_type.toNative())) {
x11.XFree(ret_prop);
String prop_name = x11.XGetAtomName(dispy, xa_prop_name);
throw new X11Exception("Invalid type of " + prop_name + " property");
}
int ret_format = ret_format_ref.getValue();
long ret_nitems = ret_nitems_ref.getValue().longValue();
// null terminate the result to make string handling easier
int nbytes;
if (ret_format == 32)
nbytes = Native.LONG_SIZE;
else if (ret_format == 16)
nbytes = Native.LONG_SIZE / 2;
else if (ret_format == 8)
nbytes = 1;
else if (ret_format == 0)
nbytes = 0;
else
throw new X11Exception("Invalid return format");
int length = Math.min((int) ret_nitems * nbytes, 4096);
byte[] ret = ret_prop.getByteArray(0, length);
x11.XFree(ret_prop);
return ret;
}

How can I make start again after gameover?? (Processing)

I want to make this game in Processing.
When in 'Switch' those are displayed case0,1,2 in same time.
I don't know how to edit it.
and after case2(gameover), press key '1' to start again.
but I think it goes to case1 when gameover situation...
How can I edit it??
PImage work[] = new PImage[3];
float workSize[] = new float[3];
float workX[] = new float[3];
float workY[] = new float[3];
float workS[] = new float[3];
PImage handA, handB;
PFont font;
int level;
boolean gameover = false;
boolean selected[] = new boolean [3];
int salary = 0;
void setup(){
size(1000,800);
background(255);
imageMode(CENTER);
for (int i=0; i<3; i++) {
workX[i] = random(0, width);
workY[i] = random(0, height);
selected[i] = false;
workSize[i] = 120;
}
handA = loadImage("handA.png");
handB = loadImage("handB.png");
work[0] = loadImage("work0.png");
work[1] = loadImage("work1.png");
work[2] = loadImage("work2.png");
font = createFont("Gulim", 48);
textFont(font);
textAlign(CENTER, CENTER);
}
void draw(){
background(255);
if (mousePressed) {
cursor(handB, 0, 0);
} else {
cursor(handA, 0, 0);
}
switch (level) {
default: // press'1' to start game
fill(0);
text("1을 눌러 일 얻기", width/2, height/2);
if (key == '1') {
level = 1;
}
break;
case 1:
game();
if (gameover == true) {
level = 2;
}
break;
case 2: // press '1' to start again
fill(0);
text("퇴직금 : "+ salary + " + (비정규직으로 퇴직금 없음)", width/2, height/2-100);
text("일을 못해서 정리해고", width/2, height/2);
text("1을 눌러 다시 일 얻기", width/2, height/2+100);
if (key == '1') {
level = 1;
}
break;
}
}
void game() {
for (int i=0; i<3; i++) {
float clickedDist = dist(workX[i], workY[i], mouseX, mouseY);
if (clickedDist<workSize[i]/2 && mousePressed) {
workSize[i] = workSize[i] - 2;
} else {
workSize[i] = workSize[i] + 0.7;
}
if (workSize[i]<100) {
workSize[i] = 0;
}
if (workSize[i]>400) {
gameover = true;
}
if (workSize[i] == 0 && selected[i] == false) {
salary = salary + 50;
selected[i] = true;
workX[i] = random(0, width);
workY[i] = random(0, height);
selected[i] = false;
workSize[i] = 120;
}
if (salary > 150) {
workS[i] = workSize[i] + 0.5;
workSize[i] = workS[i];
}
if (abs(mouseX-workX[i]) < workSize[i]/2 && abs(mouseY-workY[i]) < workSize[i]/2) {
workX[i] += random(-5,5);
workY[i] += random(-5,5);
}
image(work[i], workX[i], workY[i], workSize[i], workSize[i]);
pushMatrix();
fill(0);
textSize(48);
text("봉급 : "+ salary, textWidth("salary"), (textAscent()+textDescent()/2));
popMatrix();
}
}
All you have to do is reset any variables that store the state of your game, such as your level variable. Something like this:
void keyPressed(){
if(gameover && key == '1'){
gameover = false;
level = 1;
}
}

Linux Kernel Error

I got the same errors on these lines
error: lvalue required as left operand of assignment
line 49: for (current = root; current != NULL; ptr = current) {
line 50: current =current->link[res];
line 75: for (current = bf; current != newnode; res = link_dir[++i]) {
line 80: current = current->link[res];
line 167: current = root;
line 192: current = current->link[res];
How can I fix this?
I am using kernel version 2.6.32-24-generic
It is my one of function and above four errors are from this function...
It is an insertion function of AVL tree.
static void insertion (char value[]) {
struct AVLTree_Node *bf, *parent_bf, *subtree, *temp;
struct AVLTree_Node *current, *parent, *newnode, *ptr;
int res = 0,i=0 ,num=100, compareLimit = 100;
char link_dir[32];
if (!root) {
root = createNode(value);
return;
}
bf = parent_bf;
parent_bf = root;
// find the location for inserting the new node
for (current = root; current != NULL; ptr = current) {
current =current->link[res];
num = strcmp(value,current->data);
if (num == 0) {
printk(KERN_INFO "Cannot insert duplicates!!\n");
return;
}
int result = strncmp(value,current->data, compareLimit);
if(result > 0)
res = 1;
else if(result <= 0)
res =0;
parent = current;
if (current->bfactor != 0) {
bf = current;
parent_bf = ptr;
i = 0;
}
link_dir[i++] = res;
}
// create the new node
newnode = createNode(value);
parent->link[res] = newnode;
res = link_dir[i = 0];
// updating the height balance after insertion
for (current = bf; current != newnode; res = link_dir[++i]) {
if (res == 0)
current->bfactor--;
else
current->bfactor++;
current = current->link[res];
}
// right sub-tree
if (bf->bfactor == 2) {
printk(KERN_INFO "bfactor = 2\n");
temp = bf->link[1];
if (temp->bfactor == 1) {
subtree = temp;
bf->link[1] = temp->link[0];
temp->link[0] = bf;
temp->bfactor = bf->bfactor = 0;
} else {
subtree = temp->link[0];
temp->link[0] = subtree->link[1];
subtree->link[1] = temp;
bf->link[1] = subtree->link[0];
subtree->link[0] = bf;
// update balance factors
if (subtree->bfactor == -1) {
bf->bfactor = 0;
temp->bfactor = 1;
} else if (subtree->bfactor == 0) {
bf->bfactor = 0;
temp->bfactor = 0;
} else if (subtree->bfactor == 1) {
bf->bfactor = -1;
temp->bfactor = 0;
}
subtree->bfactor = 0;
}
// left sub-tree
} else if (bf->bfactor == -2) {
temp = bf->link[0];
if (temp->bfactor == -1) {
// single rotation(SR) right
subtree = temp;
bf->link[0] = temp->link[1];
temp->link[1] = bf;
temp->bfactor = bf->bfactor = 0;
} else {
// double rotation - (SR left + SR right)
subtree = temp->link[1];
temp->link[1] = subtree->link[0];
subtree->link[0] = temp;
bf->link[0] = subtree->link[1];
subtree->link[1] = bf;
// update balance factors
if (subtree->bfactor == -1) {
bf->bfactor = 1;
temp->bfactor = 0;
} else if (subtree->bfactor == 0) {
bf->bfactor = 0;
temp->bfactor = 0;
} else if (subtree->bfactor == 1) {
bf->bfactor = 0;
temp->bfactor = -1;
}
subtree->bfactor = 0;
}
} else {
return;
}
if (bf == root) {
root = subtree;
return;
}
if (bf != parent_bf->link[0]) {
parent_bf->link[1] = subtree;
} else {
parent_bf->link[0] = subtree;
}
return;
}
current is a macro that expands into a function call:
static __always_inline struct task_struct *get_current(void)
{
return this_cpu_read_stable(current_task);
}
#define current get_current()
Use some other variable name.

Extracting a portion of Image in C#

I have made a C# Windows application with two Picture-Boxes one as MainPictureBox and other as ThumbnailBox, I want to Extract a portion of Image upon moving mouse over Main Image and load it into ThumbnailPictureBox.
Here is a way to get a thumbnail from the image.
public static Bitmap Thumb(this Image inputStream, int width, int height)
{
using (var bitMap = new Bitmap(inputStream))
{
int originalWidth = bitMap.Width;
int originalHeight = bitMap.Height;
int startPositionHeight = 0;
int startPosionWidth = 0;
int widthHeight = 0;
if (originalWidth > originalHeight)
{
startPosionWidth = (originalWidth - originalHeight) / 2;
widthHeight = originalHeight;
}
else if (originalHeight > originalWidth)
{
startPositionHeight = (originalHeight - originalWidth) / 2;
widthHeight = originalWidth;
}
else if (originalWidth == originalHeight)
{
widthHeight = originalHeight;
}
var rect = new Rectangle(startPosionWidth, startPositionHeight, widthHeight, widthHeight);
using (Bitmap cropped = bitMap.Clone(rect, bitMap.PixelFormat))
{
using (var newbitmap = new Bitmap(cropped, width, height))
{
var stream = new MemoryStream();
newbitmap.Save(stream, ImageFormat.Tiff);
stream.Position = 0;
return new Bitmap(stream);
}
}
}
}

Out of memory error native Image decode Error while loading image to gallery

I am trying to load image from a folder into my application, the code I am using is
FileConnection fc = null;
DataInputStream in = null;
DataOutputStream out = null;
try {
fc = (FileConnection)Connector.open("file:///e:/Images/Abc.jpg");
int length = (int)fc.fileSize();//possible loss of precision may throw error
byte[] data = null;
if (length != -1) {
data = new byte[length];
in = new DataInputStream(fc.openInputStream());
in.readFully(data);
}
else {
int chunkSize = 112;
int index = 0;
int readLength = 0;
in = new DataInputStream(fc.openInputStream());
data = new byte[chunkSize];
do {
if (data.length < index + chunkSize) {
byte[] newData = new byte[index + chunkSize];
System.arraycopy(data, 0, newData, 0, data.length);
data = newData;
}
readLength = in.read(data, index, chunkSize);
index += readLength;
} while (readLength == chunkSize);
length = index;
}
Image image = Image.createImage(data, 0, length);
image = createThumbnail(image);
ImageItem imageItem = new ImageItem(null, image, 0, null);
mForm.append(imageItem);
mForm.setTitle("Done.");
fc = (FileConnection)Connector.open("file:///e:/Images/Abc.jpg");
if(!fc.exists()){
try{
fc.create();
}catch(Exception ce){System.out.print("Create Error: " + ce);}
}
out = new DataOutputStream(fc.openOutputStream());
out.write(data);
}
catch (IOException ioe) {
StringItem stringItem = new StringItem(null, ioe.toString());
mForm.append(stringItem);
mForm.setTitle("Done.");
}
finally {
try {
if (in != null) in.close();
if (fc != null) fc.close();
}
catch (IOException ioe) {}
hope it can be the problem with image I tried to resize the image
private Image createThumbnail(Image image)
{
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
int thumbWidth = 18;
int thumbHeight = 23;
Image thumb = Image.createImage(thumbWidth, thumbHeight);
Graphics g = thumb.getGraphics();
for (int y = 0; y < thumbHeight; y++)
{
for (int x = 0; x < thumbWidth; x++)
{
g.setClip(x, y, 1, 1);
int dx = x * sourceWidth / thumbWidth;
int dy = y * sourceHeight / thumbHeight;
g.drawImage(image, x - dx, y - dy, Graphics.LEFT | Graphics.TOP);
}
}
Image immutableThumb = Image.createImage(thumb);
return immutableThumb;
}
Still it returns an exception out of memmory native image deocde error, Somebody pls help me to sort it out
This may occur becuase of two reason.
Image size: In some phones due to small heap size not device does not load image so try with smaller image size.
Second reason may be image is corrupt so try with another image.

Resources