PixelGrabber.getPixels returns an int[] full of -1's
I'm trying to get the pixels of a certain area of a screen shot but all I can get is an array full of -1's. I'm trying to get the RGB values so I can compare them against another image. Can anyone look at my code and suggest a fix or new method? Thanks. private void takeScreenShot() throws AWTException, IOException {
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(bounds);
PixelGrabber grabber = new PixelGrabber(image,550,320,20,18,false);
try {
grabber.grabPixels();
} catch (InterruptedException ex) {
ex.printStackTrace();
int[] data = grabber.getPixels();
}
Ok, I tried BufferedImage.getRGB() but it still returns all -1's in the array. Here is the updated code:private void takeScreenShot() throws AWTException, IOException {
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(bounds);
int[] data = new int[20*18];
image.getRGB(520,320,20,18,data,0,20);
}
Similar Messages
-
Need help returning an Int!!!
here is the code for my sport quiz class:
import javax.swing.*;
public class Sport
public static int main (String []args)
Object[] sportValues = { "Freddie", "jimbo", "the destroyer" };
Object sportq1;
Object[] sportValues2 = { "David Beckham", "Alessandro Del Piero",
"Michael Ballack" };
Object sportq2;
Object[] sportValues3 = { "6", "10", "14" };
Object sportq3;
int sportScore = 0;
String message;
//............QUESTION 1..............
sportq1 = JOptionPane.showInputDialog(null, "Question 1: What nickname is given to england cricketer andrew flintoff?", "selection", JOptionPane.YES_NO_CANCEL_OPTION, null,
sportValues, sportValues[0]);
if (sportq1.equals(sportValues[0]))
message = "CORRECT!";
JOptionPane.showMessageDialog(null, message);
sportScore = (sportScore+1);
else
message = "WRONG!";
JOptionPane.showMessageDialog(null, message);
//............QUESTION 2.............
sportq2 = JOptionPane.showInputDialog(null, "Question 2: Who scored italy's second goal in the world cup final?", "selection", JOptionPane.YES_NO_CANCEL_OPTION, null,
sportValues2, sportValues2[0]);
if (sportq2.equals(sportValues2[1]))
message = "CORRECT!";
JOptionPane.showMessageDialog(null, message);
sportScore = (sportScore+1);
else
message = "WRONG!";
JOptionPane.showMessageDialog(null, message);
//............QUESTION 3.............
sportq3 = JOptionPane.showInputDialog(null, "Question 3: how many players are there in an ice hockey team?", "selection", JOptionPane.YES_NO_CANCEL_OPTION, null,
sportValues3, sportValues3[0]);
if (sportq3.equals(sportValues3[0]))
message = "CORRECT!";
JOptionPane.showMessageDialog(null, message);
sportScore = (sportScore+1);
else
message = "WRONG!";
JOptionPane.showMessageDialog(null, message);
return sportScore;
i am trying to return the 'sportScore' int to a main quiz class but for some reason it hasnt worked...
can anyone tell me what i have done wrong?
thanks alot!this is my main quiz class:
import javax.swing.*;
public class Quiz
public static void main (String []args)
Object[] possibleValues = { "Sport", "Music", "General Knowledge", "TV and Film", "Display Score Board" };
Object choice;
do
choice = JOptionPane.showInputDialog(null,"Welcome to my quiz\nPlease select you category:", "selection", JOptionPane.YES_NO_CANCEL_OPTION, null,
possibleValues, possibleValues[0]);
if (choice.equals(JOptionPane.CANCEL_OPTION))
System.exit(0);
if (choice.equals(possibleValues[0]))
Sport.doQuiz();
if (choice.equals(possibleValues[1]))
Music.doQuiz();
if (choice.equals(possibleValues[2]))
General.doQuiz();
if (choice.equals(possibleValues[3]))
TV.doQuiz();
if (choice.equals(possibleValues[4]))
int sportScore = Sport.doQuiz();
int tvScore = TV.doQuiz();
int musicScore = Music.doQuiz();
int generalScore = General.doQuiz();
int totalScore = (sportScore+tvScore+musicScore+generalScore);
JOptionPane.showMessageDialog(null,"Thankyou for taking my quiz!\nhere are your results:\nSport: "
+ sportScore + "/3\nMusic: " + musicScore + "/3\nGeneral Knowledge: "
+ generalScore + "/3\nTV and Film: " + tvScore +"/3\n\nTOTAL: "
+ totalScore + "/12!");
while(!(choice.equals(possibleValues[4])));
}as you can see i have more than just the sport category but once i know how to do that one i will be able to do the rest...
now here is my sport class:
import javax.swing.*;
public class Sport
public static int doQuiz()
Object[] sportValues = { "Freddie", "jimbo", "the destroyer" };
Object sportq1;
Object[] sportValues2 = { "David Beckham", "Alessandro Del Piero",
"Michael Ballack" };
Object sportq2;
Object[] sportValues3 = { "6", "10", "14" };
Object sportq3;
int sportScore = 0;
String message;
//............QUESTION 1..............
sportq1 = JOptionPane.showInputDialog(null, "Question 1: What nickname is given to england cricketer andrew flintoff?", "selection", JOptionPane.YES_NO_CANCEL_OPTION, null,
sportValues, sportValues[0]);
if (sportq1.equals(sportValues[0]))
message = "CORRECT!";
JOptionPane.showMessageDialog(null, message);
sportScore = (sportScore+1);
else
message = "WRONG!";
JOptionPane.showMessageDialog(null, message);
//............QUESTION 2.............
sportq2 = JOptionPane.showInputDialog(null, "Question 2: Who scored italy's second goal in the world cup final?", "selection", JOptionPane.YES_NO_CANCEL_OPTION, null,
sportValues2, sportValues2[0]);
if (sportq2.equals(sportValues2[1]))
message = "CORRECT!";
JOptionPane.showMessageDialog(null, message);
sportScore = (sportScore+1);
else
message = "WRONG!";
JOptionPane.showMessageDialog(null, message);
//............QUESTION 3.............
sportq3 = JOptionPane.showInputDialog(null, "Question 3: how many players are there in an ice hockey team?", "selection", JOptionPane.YES_NO_CANCEL_OPTION, null,
sportValues3, sportValues3[0]);
if (sportq3.equals(sportValues3[0]))
message = "CORRECT!";
JOptionPane.showMessageDialog(null, message);
sportScore = (sportScore+1);
else
message = "WRONG!";
JOptionPane.showMessageDialog(null, message);
return sportScore;
}i am tring to return sportScore from the sport class to the main quiz class, at the moment instead of getting the sportScore at the end of the quiz class it is now running the whole sport class again!
what have i done wrong?
ta -
The Dock keeps returning in Quicktime full screen mode
Hi all, hope someone has some insight as this is really starting to get to me...
when watching stuff in QT every time at some point the dock will reappear on top of the movie and i will have to cmd+F out and back in to get rid of it, sometimes it comes up within minutes other times it can take up to 30 mins or so... its been happening for a few months now... i have noticed if i have adium open with my contact list on auto hide to the side that it will come up with the dock but will promptly autohide again, where as the dock stays visible.
Thanks
HarroI had this problem a while back when i upgraded from Tiger, then somewhere along the way, one of the updates fixed it. I recently did a clean format and created a new user account, lo and behold, it's back... This time with Adium X too!
Message was edited by: qwertyjem -
...
You can try to spoof the user agent as Firefox 5 to see if that works.
*Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0
*https://addons.mozilla.org/firefox/addon/user-agent-switcher/
*https://addons.mozilla.org/firefox/addon/belgium-eid/ -
Only ints return from SQLite queries with calculations
Howdy. Hope I have the right forum for this question.
I'm on a project using a SQLite database in Flex 4 and I'm using the following SQL query:
SELECT max(totalScore) AS score,
max(longestStreak) AS streakLen,
max((correctNotes * 100) / totalNotes) AS accuracyPercent
FROM main.practiceRecord rec
JOIN main.lessonSession sess
ON rec.sessionGuid = sess.guid
WHERE sess.purchasedLessonID = :lessonId
The query is working fine as it is written. The problem is that when I do the calculation ((correctNotes * 100) / totalNotes) to return a percent value, I'd like to do it without having to multiply by 100, since I generally treat percentages as numbers between 0 and 1 (.68 = 68%). If I don't multiple by 100 in the query, however, I get a "0" for anything less than 1, so only 100% returns with the correct value. It appears that this kind of calculation only returns an int, as opposed to a REAL (or its AS3 corresponding "Number").
Is there something that I can do to return a value between 0 and 1 for this percentage so that I don't have to multiply by 100 in the query and then divide by 100 when I get the result? Is there a function that allows me to specify the precision for the returned value?
Thanks for your time,
BryanMaybe Tom Kyte's "trick" of the "select pl_sql_function () from dual" to invoke scalar subquery caching can help you:
select ename
from emp, dept
where (select dname_lookup(emp.deptno) from dual) = 'SALES'
and dept.deptno = 30
and emp.deptno = dept.deptno;http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1547006324238
As Tom says, in 11g you'll be able to cache that function (new 11g feature) which removes the need for the "trick":
Oracle® Database PL/SQL Language Reference 11g Release 1 (11.1)
- 8 Using PL/SQL Subprograms
-- Using the Cross-Session PL/SQL Function Result Cache
http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28370/subprograms.htm#BABFHACJ
"On the PL/SQL Function Result Cache" by Steven Feuerstein
http://www.oracle.com/technology/oramag/oracle/07-sep/o57plsql.html
Regards,
Zlatko -
How do i return nothing in a "public int getNothing()" method ?
i'd like "getNothing" to return an int ONLY if "z" is true ... is that even possible ?
code :
public int getNothing() {
boolean z= trueOrFalse();
int i = generator.nextInt(10);
if (z=true){
return i;
Message was edited by:
jeroenQuantbut in this case it's kinda necessary ...It isn't possible, so it isn't necessary.
If getNothing() returns an int within a certain range, then you could return an int outside this range if trueOrFalse() is false. For example getNothing() could return a positive int when the condition is true and a -1 otherwise. The caller could detect the out of range value and act appropriately.
Another approach is to move the boolean test from the getNothing() method to its caller. Ie something like:public void test() {
if(trueOrFalse()) {
System.out.println(getNothing());
public int getNothing() {
return generator.nextInt(10);
} -
How do I return to the old full screen bookmarks display?
Using Safari 7.0.3 and OS 10.9.2 I find the bookmarks display most unsatisfactory. I don't like the sidebar. I want to return to the full screen display of the folders and names at the bottom so I can rea the whole link title, with the option of scrubing through the site images above, iTunes style.
The current configuration is awkward because I have to click on each bookmark link to see it.
Thanks for your helpTry "Edit Bookmarks".
Click "Bookmarks" in the Safari menubar and then select " Edit Bookmarks". -
PixelGrabber in Win2k -- Please Help
I am running win2k server and am using PixelGrabber to grab the pixels of every thing that has been drawn on my panel. This is the function but the grabpixels does not return integer values corresponding ot the current Foreground and back ground color of the panel.
Is there a way out? Is there some specific colors that I can use?
PLEASE HELP! My project dead line is very near.
public int[] getPixels() throws InterruptedException{
int Height = this.getHeight();
int Width = this.getWidth();
Image img = createImage(Width,Height);
Graphics g = img.getGraphics();
this.paint(g);
int[] l_pixels = new int[Width * Height];
PixelGrabber pg = new PixelGrabber(img,0,0,Width,Height, l_pixels, 0,Width);
pg.grabPixels();
g.dispose();
return l_pixels;Hi,
if you are using SWING get pixels from RepaintManager object (it is static and one instance per application).
Vitally -
Public int move(CDRack anotherRack)
I have problems with method: move(CDRack anotherRack).
It removes CDs from anotherRack, but the rack I'm trying to fill in with anotherRack's CDs is filled with a one same CD from the anotherRack not various CDs as it should.. hard to explain.:)
Is some willing to give me tips? And is there some other way
to use insert method with the help of the move-method?
/**Class CDRack represents collections of compact discs. Discs are
located in the rack in slots numbered from zero upwards.The discs are
represented by Record objects and empty slots by null values. */
public class CDRack extends Object {
private Record[] collection;
/**Creates a new, empty CD rack. Parameters:size - the size of the new
rack, i.e. the number of slots it has */
public CDRack(int size) {
collection = new Record[size];
this.size = size;
/**Inserts a cd in the given rack slot if the slot in question is
empty. Parameters: disc - the cd to be added in the rackslot - the
number of a (hopefully empty) slot
Returns: a boolean value indicating if the insertion was successful.
public boolean insert(Record disc, int slot) {
if (collection[slot]==null)) {
collection[slot] = record;
return true;
else return false;
/** Inserts the given cd in the first empty rack slot (if there is even
one empty slot in the rack).
Parameters: disc - the disc to be added in the rack
Returns:
the number of the slot where the disc was added, or a negative number
if the rack was already full */
public int insert(Record disc) {
for(slot=0; slot<collection.length; slot++) {
if(collection[slot]==null) {
collection[slot] = disc;
return slot;
return -1; //not enough place
/** Moves all the discs from the given cd rack to this rack. The cds
from the other rack are inserted in the empty slots of this rack (in
ascending numerical order of slot numbers) in the order in which they
are located in the other rack. The moved discs are removed from their
original rack. Even if there is not enough space for all the discs in
this rack, as many cds are moved as possible.
Parameters:
anotherRack - another rack whose cds are to be moved into this one
Returns:
the number of cds moved from the other rack to this one */
public int move(CDRack anotherRack) {
int howMuchPlace = this.getSize() - this.getNumberOfCDs();
if(anotherRack.getNumberOfCDs() <= howMuchPlace) {
for(int i=0; i<anotherRack.getNumberOfCDs()+1; i++) {
this.insert(disc);
for(slot=0; slot<anotherRack.getNumberOfCDs()+1; i++) {
anotherRack.remove(slot);
return anotherRack.getNumberOfCDs();
if(anotherRack.getNumberOfCDs() > howMuchPlace) {
for(int i=0; i<howMuchPlace+1; i++) {
this.insert(disc);
for(slot=0; slot<howMuchPlace+1; i++) {
anotherRack.remove(slot);
return howMuchPlace;
return -1;I'm about to leave the office (it's 7PM in London and
there at least a dozen beers with my name on them ;)
but I'll take a look on Monday and see how you got
on.Sheesh. Must be Christmas or something :)
You still need to implement organize() and sortAlphabetically(), plus move the classes to their own files and modify the parameter names to match the assignment.
But, apart form that, here's what you wanted.
Now, I realy am going to ge those beers...
public class Maria2
static class Record {}
static class CDRack
private Record[] mRecords;
CDRack(int size) { mRecords= new Record[size]; }
int find(Record disk)
for (int i= 0; i < mRecords.length; i++) {
if (mRecords.equals(disk))
return i;
return -1;
Record getCD(int index)
if (index < 0 || index >= mRecords.length)
return null;
return mRecords[index];
int getNumberOfCDs() { return getSize() -available(); }
int getSize() { return mRecords.length; }
int insert(Record record)
int index= 0;
for (; index < mRecords.length && mRecords[index] != null; index++);
if (insert(record, index))
return index;
return -1;
boolean insert(Record record, int index)
if (index >= mRecords.length)
return false;
if (mRecords[index] != null)
return false;
mRecords[index]= record;
return true;
private int available()
int available= 0;
for (int i= 0; i < mRecords.length; i++) {
if (mRecords[i] == null )
available++;
return available;
Record remove(int index)
Record record= getCD(index);
mRecords[index]= null;
return record;
int move(CDRack source)
int moved= 0;
for (int i= 0; i< source.getSize(); i++) {
Record record= source.getCD(i);
if (record == null)
continue;
if (insert(record) < 0)
break;
source.remove(i);
moved++;
return moved;
public static void main(String[] argv)
CDRack rack1= new CDRack(32);
CDRack rack2= new CDRack(18);
for (int i= 0; i< rack1.getSize()/2; i++)
rack1.insert(new Record(), i*2);
for (int i= 0; i< rack2.getSize(); i++)
rack2.insert(new Record(), i);
System.err.println("Rack one has " rack1.getNumberOfCDs() " records");
System.err.println("Rack two has " rack2.getNumberOfCDs() " records");
int moved= rack1.move(rack2);
System.err.println(moved +" records were moved");
System.err.println("Rack one has " rack1.getNumberOfCDs() " records");
System.err.println("Rack two has " rack2.getNumberOfCDs() " records"); -
JNI_CreateJavaVM returns JNI_ENOMEM (-4) from different versions of the jre
I have created a JNI dll, invoked from a VBA Excel add-in to execute Java code. This works fine until I introduce the -Xmx parameter as a vm option.
Before creating the VM, I use a VirtualAlloc/Free loop to make sure the -Xmx parameter is not too large, decrementing it by 2MB each time until an allocable amount is found (thanks to [jurberg's post|http://forums.sun.com/thread.jspa?forumID=37&threadID=5220601]; my version, slightly modified, is posted below). I then pass that value to the VM via the -Xmx option.
This works great when I am using a JRE 1.6 installed in the "C:\Program Files\Java\*jre1.6.0_xx"* directory. When the same* JRE version is installed in the "C:\Program Files\Java\*jre6*" directory, JNI_CreateJavaVM fails with JNI_ENOMEM. Calling GetLastError returns 0 ("operation completed successfully"). Using a *1.5 JRE*, this also fails, returning JNI_ENOMEM, but GetLastError returns error code 6 ("the handle is invalid").
A little about my platform:
Windows XP Pro
Building JNI dll using Microsoft Visual C++ 2008 and 1.5 JDK
I have multiple JREs and JDKs installed on my system as this is a dev machine, but I have the same problem on a non-dev machine running XP Home.
Here is a snippet of my code used to create the vm:
// create the JNI structures
const int numOptions = args.size();
JavaVMInitArgs vm_args;
JavaVMOption* options = new JavaVMOption[numOptions];
log("Creating JVM with parameters:");
int i = 0;
char * nextArg;
for (itr=args.begin(); itr != args.end(); itr++) {
nextArg = new char[(*itr).length() + 1];
strcpy(nextArg, (*itr).c_str());
options.extraInfo = NULL;
options[i++].optionString = nextArg;
log("\t" + string(nextArg));
vm_args.version = CRUSH_JNI_VERSION;
vm_args.options = options;
vm_args.nOptions = numOptions;
vm_args.ignoreUnrecognized = JNI_FALSE;
// load and initialize the Java VM, and return a JNI interface pointer
JNIEnv* env = NULL;
err = (*createVM)(&jvm, (void**)&env, &vm_args);
// err is -4 (JNI_ENOMEM) in the cases described above
Does anyone have any suggestions on what is going on here and how I might make this code stable for all 1.5 and 1.6 JREs, regardless of where they are installed?
Thanks in advance,
Sarah
Code to determine max -Xmx value:static const DWORD NUM_BYTES_PER_MB = 1024 * 1024;
bool canAllocate(DWORD bytes)
LPVOID lpvBase;
lpvBase = VirtualAlloc(NULL, bytes, MEM_RESERVE, PAGE_READWRITE);
if (lpvBase == NULL) return false;
VirtualFree(lpvBase, 0, MEM_RELEASE);
return true;
int getMaxHeapAvailable(int permGenMB, int maxHeapMB)
DWORD originalMaxHeapBytes = 0;
DWORD maxHeapBytes = 0;
int numMemChunks = 0;
SYSTEM_INFO sSysInfo;
DWORD maxPermBytes = permGenMB * NUM_BYTES_PER_MB; // Perm space is in addition to the heap size
DWORD numBytesNeeded = 0;
GetSystemInfo(&sSysInfo);
// jvm aligns as follows:
// quoted from size_t GenCollectorPolicy::compute_max_alignment() of jdk 7 hotspot code:
// The card marking array and the offset arrays for old generations are
// committed in os pages as well. Make sure they are entirely full (to
// avoid partial page problems), e.g. if 512 bytes heap corresponds to 1
// byte entry and the os page size is 4096, the maximum heap size should
// be 512*4096 = 2MB aligned.
// card_size computation from CardTableModRefBS::SomePublicConstants of jdk 7 hotspot code
int card_shift = 9;
int card_size = 1 << card_shift;
DWORD alignmentBytes = sSysInfo.dwPageSize * card_size;
maxHeapBytes = maxHeapMB * NUM_BYTES_PER_MB;
// make it fit in the alignment structure
maxHeapBytes = maxHeapBytes + (maxHeapBytes % alignmentBytes);
numMemChunks = maxHeapBytes / alignmentBytes;
originalMaxHeapBytes = maxHeapBytes;
// loop and decrement requested amount by one chunk
// until the available amount is found
numBytesNeeded = maxHeapBytes + maxPermBytes;
while (!canAllocate(numBytesNeeded) && numMemChunks > 0)
numMemChunks --;
maxHeapBytes = numMemChunks * alignmentBytes;
numBytesNeeded = maxHeapBytes + maxPermBytes;
if (numMemChunks == 0) return 0;
// we can allocate the requested size, return it now
if (maxHeapBytes == originalMaxHeapBytes) return maxHeapMB;
// calculate the new MaxHeapSize in megabytes
return maxHeapBytes / NUM_BYTES_PER_MB;I have a similar, but I think much simpler problem. Namely, I get ENOMEM's when as far as I can tell there's plenty of memory available. It seems to have something to do with how Windows is configured, although I've never been able to determine what it could be.FWIW, in my case, I found that if I loaded my JNI dll into a console process, the max heap requested was always allocated. But when loading into Excel, the same amount would be too much. This was partly due to the fact that Excel has its own memory management, limiting the amount of memory workbooks can use. Also, it could be due to the vm not being able to reserve a contiguous chunk of memory for the max heap space.
Why (and how) separate the permanent generation space from the rest of the max heap? It seems you'll fail if you can't get that much space (which is the why) but how did you determine what it is?The VM uses the perm gen space plus the requested max heap space when attempting the VirtualAlloc call to verify that it can allocate the specified amount. The default perm gen is 64MB, but that can be changed via the -XX:MaxPermSize vm parameter, so I allow for any requested value.
What's CRUSH_JNI_VERSION? It's not in any .h file I have.That's just my own constant defined to be either JNI_VERSION_1_4 or JNI_VERSION_1_6.
Why are you messing with the bootclasspath? (I suspect you're adding something to it. Generally the VM can find it's own damn classpath).Yep, I'm adding the 2.1 JAXB jar to the bootclasspath because earlier 1.6 distributions included JAXB 2.0 and I needed 2.1.
-sarah -
Process.exitValue() only returns the low byte of the exit code?
Hi - I'm executing a subprocess and then waiting for it to return, and then examining the exit code of the subprocess. The error the subprocess returns is 0xb03, but exitValue() only sees 0x03. Further testing shows that if I return 0xbff from my native process, exitValue() or waitFor() will only return 0xff. I expanded this further to return 0xfffffbff, and sure enough, the Process methods only return 0xff.
Anyone know what the deal is here? The return type for exitValue() and waitFor() are both 'int', so it seems reasonable to be able to return values up to 0xffffffff. Is there a way to set this up to sue the full int?
Thanks for any insight.OK, that explains it. I think we had taken the fact that main() returns and int on *NIX that you could return anything that fit in an int into the exit code. I've now found some corroboration that you can only return a value of 0-255.
This also explains why we have never seen this issue on Windows - apparently you can return much larger values on Windows.
Thanks for the assist! -
GrabFrame() to return a string of pixel information?
Hi everyone,
Basically what im looking for is creating a 2d array of values(but id be happy with a string) corrosponding to each of the 320*240 pixels of my camera. At the moment i can get back an awt image using:
Buffer buf = frameGrabber.grabFrame();
Image img = (new BufferToImage((VideoFormat) buf.getFormat()).createImage(buf));
I would of thought that i should meerly use the toString() method. But if i toString() buf i get:
javax.media.Buffer@22c95b
and if i toString() img i get:
BufferedImage@22c95b: type = 1 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0 IntegerInterleavedRaster: width = 320 height = 240 #Bands = 3 xOff = 0 yOff = 0 dataOffset[0] 0
If anyone could help, and point me in the direction of the right method to use, i would be greatly appreciative.
Thanks.You will need integer values from an image to do anything meaningful with the data. Something like this -
int redValues = new int[imageWidth * imageHeight];
int greenValues = new int[imageWidth * imageHeight];
int blueValues = new int[imageWidth * imageHeight];
int alphaValues = new int[imageWidth * imageHeight];
int counter = 0;
public void grabEveryPixelInThe Image(Image img, int x, int y, int w, int h) {
int[] pixels = new int[w * h];
PixelGrabber pg = new PixelGrabber(img, x, y, w, h, pixels, 0, w);
try {
pg.grabPixels();
} catch (InterruptedException e) {
System.err.println("interrupted waiting for pixels!");
return;
if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
System.err.println("image fetch aborted or errored");
return;
for (int j = 0; j < h; j++) {
for (int i = 0; i < w; i++) {
doOnePixel(pixels[j * w + i]);
public void doOnePixel( int pixel) {
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel ) & 0xff;
redValues[ counter] = red ;
greenValues [ counter] = green ;
blueValues [ counter] = blue ;
AlphaValues [ counter ] = alpha ;
counter++;
}regards -
Multiple return values (Bug-ID 4222792)
I had exactly the same request for the same 3 reasons: strong type safety and code correctness verification at compile-time, code readability and ease of mantenance, performance.
Here is what Sun replied to me:
Autoboxing and varargs are provided as part of
JSRs 14 and 201
http://jcp.org/en/jsr/detail?id=14
http://jcp.org/en/jsr/detail?id=201
See also:
http://forum.java.sun.com/forum.jsp?forum=316
http://developer.java.sun.com/developer/earlyAccess/adding_generics/index.html
Multiple return values is covered by Bug-ID 4222792
Typically this is done by returning an array.
http://developer.java.sun.com/developer/bugParade/bugs/4222792.html
That's exactly the problem: we dynamically create instances of array objects that would better fit well within the operand stack without stressing the garbage collector with temporary Array object instances (and with their backing store: 2 separate allocations that need to be recycled when it is clearly a pollution that the operand stack would clean up more efficiently)
If you would like to engage in a discussion with the Java Language developers, the Generics forum would be a better place:
http://forum.java.sun.com/forum.jsp?forum=316
I know that (my report was already refering to the JSR for language extension) Generics is not what I was refering to (even if a generic could handle multiple return values, it would still be an allocated Object
instance to pack them, i.e. just less convenient than using a static class for type safety.
The most common case of multiple return values involve values that have known static datatypes and that should be checked with strong typesafety.
The simple case that involves returning two ints then will require at least two object instances and will not solve the garbage collection overhead.
Using a array of variable objects is exactly similar, except that it requires two instances for the components and one instance for the generic array container. Using extra method parameters with Integer, Byte, ... boxing objects is more efficient, but for now the only practical solution (which causes the least pollution in the VM allocator and garbage collector) is to use a custom class to store the return values in a single instance.
This is not natural, and needlessly complexifies many interfaces.
So to avoid this pollution, some solutions are used such as packing two ints into a long and returning a long, depacking the long after return (not quite clean but still much faster at run-time for methods that need to be used with high frequencies within the application. In some case, the only way to cut down the overhead is to inline methods within the caller code, and this does not help code maintenance by splitting the implementation into small methods (something that C++ can do very easily, both because it supports native types parameters by reference, and because it also supports inline methods).
Finally, suppose we don't want to use tricky code, difficult to maintain, then we'll have to use boxing Object types to allow passing arguments by reference. Shamely boxed native types cannot be allocated on the operand stack as local variables, so we need to instanciate these local variables before call, and we loose the capacity to track the cases where these local variables are not really initialized by an effective call to the method that will assign them. This does not help debugging, and is against the concept of a strongly typed language like Java should be:
Java makes lots of efforts to track uninitialized variables, but has no way to determine if an already instanciated Object instance refered in a local variable has effectively received an effective assignment because only the instanciation is kept. A typical code will then need to be written like this:
Integer a = null;
Integer b = null;
if (some condition) {
//call.method(a, b, 0, 1, "dummy input arg");
// the method is supposed to have assigned a value to a and b,
// but can't if a and b have not been instanciated, so we perform:
call.method(a = new Integer(), b = new Integer(), 0, 1, "dummy input
arg");
// we must suppose that the method has modified (not initialized!)
the value
// of a and b instances.
now.use(a.value(), b.value())
// are we sure here that a and b have received a value????
// the code may be detected at run-time (a null exception)
// or completely undetected (the method() above was called but it
// forgot to assign a value to its referenced objects a and b, in which
// case we are calling in fact: now.use(0, 0); with the default values
// or a and b, assigned when they were instanciated)
Very tricky... Hard to debug. It would be much simpler if we just used:
int a;
int b;
if (some condition) {
(a, b) = call.method(0, 1, "dummy input arg");
now.use(a, b);
The compiler would immediately detect the case where a and b are in fact not always initialized (possible use bere initialization), and the first invoked call.method() would not have to check if its arguments are not null, it would not compile if it forgets to return two values in some code path...
There's no need to provide extra boxing objects in the source as well as at run-time, and there's no stress added to the VM allocator or garbage collector simply because return values are only allocated on the perand stack by the caller, directly instanciated within the callee which MUST (checked at compile-time) create such instances by using the return statement to instanciate them, and the caller now just needs to use directly the variables which were referenced before call (here a and b). Clean and mean. And it allows strong typechecking as well (so this is a real help for programmers.
Note that the signature of the method() above is:
class call {
(int, int) method(int, int, String) { ... }
id est:
class "call", member name "method", member type "(IILjava.lang.string;)II"
This last signature means that the method can only be called by returning the value into a pair of variables of type int, or using the return value as a pair of actual arguments for another method call such as:
call.method(call.method("dummy input arg"), "other dummy input arg")
This is strongly typed and convenient to write and debug and very efficient at run-time...Can anyone give me some real-world examples where
multiple return values aren't better captured in a
class that logically groups those values? I can of
course give hundreds of examples for why it's better
to capture method arguments as multiple values instead
of as one "logical object", but whenever I've hankered
for multiple return values, I end up rethinking my
strategy and rewriting my code to be better Object
Oriented.I'd personally say you're usually right. There's almost always a O-O way of avoiding the situation.
Sometimes though, you really do just want to return "two ints" from a function. There's no logical object you can think of to put them in. So you end up polluting the namespace:
public class MyUsefulClass {
public TwoInts calculateSomething(int a, int b, int c) {
public static class TwoInts {
//now, do I use two public int fields here, making it
//in essence a struct?
//or do I make my two ints private & final, which
//requires a constructor & two getters?
//and while I'm at it, is it worth implementing
//equals(), how about hashCode()? clone()?
//readResolve() ?
}The answer to most of the questions for something as simple as "TwoInts" is usually "no: its not worth implementing those methods", but I still have to think about them.
More to the point, the TwoInts class looks so ugly polluting the top level namespace like that, MyUsefulClass.TwoInts is public, that I don't think I've ever actually created that class. I always find some way to avoid it, even if the workaround is just as ugly.
For myself, I'd like to see some simple pass-by-value "Tuple" type. My fear is it'd be abused as a way for lazy programmers to avoid creating objects when they should have a logical type for readability & maintainability.
Anyone who has maintained code where someone has passed in all their arguments as (mutable!) Maps, Collections and/or Arrays and "returned" values by mutating those structures knows what a nightmare it can be. Which I suppose is an argument that cuts both ways: on the one hand you can say: "why add Tuples which would be another easy thing to abuse", on the other: "why not add Tuples, given Arrays and the Collections framework already allow bad programmers to produce unmainable mush. One more feature isn't going to make a difference either way".
Ho hum. -
A getName method allways returns null, why?
I have an
ArrayList<Animals> array_list = new ArrayList<Animals>();
LinkedList<Animals> linked_list = new LinkedList<Animals>();
I want the getName() method in class NewListener to be accessed from the class NextListener which extends NewListener, and therefor should get access to the method. But when I run the program, it allways returns null. Why?
class NewListener implements ActionListener
public String name;
public void actionPerformed(ActionEvent e)
String str_name = showInputDialog(this,"Animal name: ",null);
if(str_name == null)
return;
for(int i=0; i<array_list.size(); i++)
if(array_list.get(i).getName().equalsIgnoreCase(str_name))
setName(str_name); // set the name with the setName() method
linked_list.add(array_list.get(i));
public void setName(String name)
this.name=name;
public String getName()
return name; // this line returns "null"
// return "Hello"; // this line works and returns "Hello"
class NextListener extends NewListener implements ActionListener
public void actionPerformed(ActionEvent e)
try
linked_list .removeFirst();
}catch(NoSuchElementException er)
System.out.println("Numerical value");
String info = getName()+" is in line"; // Why does the getName() method in the NewListener allways return a null?
showMessageDialog(this, info, "Notice", INFORMATION_MESSAGE);
}{code}Roxxor wrote:
Ok, I changed the name to private and I also tried with
public void setName(String name)
System.out.println("setting name on " + this + " to " + name); // <--- ADD THIS LINE
this.name=name;
}and it works. So this.name SHOULD get the value of name, but it doesn�t.
So the question is: why does getName() return null?Your code is doing exactly what you're telling it to do. One or more of your assumptions is wrong. Keep digging. Add more print statements.
Above all, you must drop the attitude that "it should work." There's a bug in your code. You have to find it. Repeating the mantra "It should work" is simply going to put blinders on and make it almost impossible to find your error. Instead, you have to think, "What did I do wrong?" and "If getName is returning null, then setName was never called or was called with null." -
Memory full.Not enough memory for operation.
To the Report Design Team,
It has been suggested that I post this issue here based on another thread I started: Re: Memory full.Not enough memory for operation.
The template contains a single 24 bit PNG image as a background in the Page Header section, plus 9 image records from a SQL Server image field over 3 pages (3 images per page). The images are all JPG at 3000x2000 (digital camera).
To summarize, we are experiencing three problems.
1. CR2008SP2 Designer issues a Memory Full error when Exporting to PDF.
2. Using a 3rd party PDF Printer (Bullzip PDF) and CR2008SP2 Designer generates a PDF, however, the CR2008SP2 API throws a "Memory full" exception suggesting Designer and API are different (see stack trace in linked message above).
3. With only 3 images on 1 page, CR2008 Designer Export to PDF takes 110 seconds to generate a 24MB PDF while our third party PDF Printer generates the same report in 17 seconds and 580KB.
Edited by: Don Williams on Sep 30, 2009 6:43 AMThe .rpt file size is 14MB with the Data Save option enabled, 12MB without Data Save. Presumably the 12MB file size is because of the 24bit PNG we have as our background.
The Designer executes the report in less than a second and we can scroll through all pages and see the image fields perfectly.
When we Export to PDF, the Designer takes a long time, eventually gets to the 77%, the 7th record and returns "Export report failed" followed by "Memory full". If we export only page 1 of the 3 pages, it also returns a Memory full error. However, when the same report is run with only 1 page, that page exports to PDF but with a ridiculously large size and export time.
The machine has 2GB of physical memory with an 8GB pagefile with Windows 2003 (latest everything). The process runs up to about 1GB before reporting the memory full error.
We've also tried a variety of other suggestions posted in the other thread with no success.
We're happy to provide the RPT file to the Report Team to diagnose the problem. Ultimately, we need to be able to produce a 15 page report with approximately 45 images.
Our preferred scenario is fixing problem 2. The CR Designer seems quite capable of rendering our report and printing it to our third party PDF printer in a timely manner with small size. However, the API reports memory full.
The API resides in a dedicated reporting web service with NO other code except for loading the report, setting parameters and printing. When executing, it uses up to about 1.1GB before reporting the error.
Are there any other suggestions for fixing what we have? Are there known problems with large images in reports? Do we need to lodge a formal support request?
Regards, Grant.
PS. Grr and my message formatting is lost when I edited this message!!!
There is a 1500 character limit and then all formatting is removed to save space. Break you posts into separate entries.
Edited by: grantph on Sep 30, 2009 2:49 AM
Maybe you are looking for
-
Ok, I have searched for months for an answer to this question to no avail, probably because no one has experienced it before. I am hoping however that you guys can help me figure this one out cause it is driving me nuts! Also, I am not entirely sure
-
Itunes 10.2.1 does not show remote speakers option
I have been having a strange issue on one of my laptops. I have two laptops - one with Windows 7 64bit and Windows XP 32 bit. On both laptops, I was able to connect to the airport express to stream music to my home theater (receiver) till a few month
-
Error during the execution of a planning function in BI 7
Dear All, I created an input ready query and took it into a workbook. I have to execute a planning function (by a button) which calculates some new data but I get the following error after I clicked on the button message: Error when inserting or
-
Generate AVI files. Convert in AVI from MOV. QUICKTIME PRO??
Hi, First of all, I'd like to ask you an apology if my problem has been solved in another post, but I couldn't find it. I have an AVI file and I'd like to add the subs (srt file) My idea was to open the AVI file with a program, to add the file and fi
-
Naming Information Cannot be Allocated VIA MSTSC
Hi, Suddenly we face some issue with our Windows 2003R2 SP2 (32 bit ) Server it has physical RAM:2GB. When we tried to Connect the server via "mstsc" getting a error message after Credential window ! Error: Naming information can not be located for f