Decode or NVL2?
What should be used when we have a choice of using decode or NVL2, how will it affect the performance?
Hi,
Nandini wrote:
I don't want to know the difference between both. I want to know which should be prefered to use.Knowing their difference means knowing how to use them and in what particular situation you may use them.
NVL2 is an extension of the functionality of NVL function which takes 3 arguments.
The syntax for the NVL2 function is:
NVL2( string1, value_if_NOT_null, value_if_null )
string1 is the string to test for a null value.
value_if_NOT_null is the value returned if string1 is not null.
value_if_null is the value returned if string1 is null.
The syntax for the DECODE function is:
decode( expression , search , result [, search , result]... [, default] )
expression is the value to compare.
search is the value that is compared against expression.
result is the value returned, if expression is equal to search.
default is optional. If no matches are found, the decode will return default. If default is omitted, then the decode statement will return null (if no matches are found).
Regards.
Similar Messages
-
Decode or nvl2 or case functions
create a query that displays employees lastname and commission amounts.if an employee does not earn commission,put "no commission."label column comm
Sample Output
lastname comm
king no commission
abel .3
Note:The column commission is of number datatypeHi,
This looks an awful lot like homework.
If you're really stuck, post your best attempt so far, and a description of what you think is wrong with it.
The assignment itself, "Decode or nvl2 or case" gives you three different ways to do this.
CASE is a lot more useful in general, so I suggest learning how to use it first.
NVL2 is a little more concise for this particular problem.
DECODE can do anything CASE can do, often with a lot more coding. Unless it's required for your schiool work, I don't suggest using DECODE.
You'll probably need to use the TO_CHAR function, to convert the commission to a string, so that whatever kind of expression you use (CASE or NVL2 or DECODE) it will always return the same datatype: VARCHAR2.
All built-in functions are documented in the SQL Language manual:
http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/index.htm
Actually, CASE and DECODE are not functions, but they're described in the same manual,. -
Case and decode - nested functions
Can i use a case statement inside a decode or nvl2 function?
eg.
decode(col_a,'ABC',
case when col_b in (1,2) then 'CCC' else when col_b in (3,4,5) then 'XXX' end
, 'NA')
Can i use a function like this basically, can i nest a case statement within a decode or nvl2 function?
I have used nested decodes and nvls and nested case statements but not combined both so far.... so need an opinion...
Thanks.
Edited by: user254668 on Apr 30, 2010 1:35 PMuser254668 wrote:
Can i use a case statement inside a decode or nvl2 function? Absolutely. Just get rid of that else:
decode(col_a,'ABC',
case when col_b in (1,2) then 'CCC' when col_b in (3,4,5) then 'XXX' end
, 'NA') SY. -
Hello, just starting to learn PL/SQL. I have a query which runs just fine and it has a case statement. When I take that query and place it into a procedure and compile, it gives me a compile error stating "ENCOUNTERED symbol CASE when expecting... providing a list of symbols.
This procedure is part of a package, so I am only showing the procedure portion...
PROCEDURE QRY_USERS (oRows OUT t_cursor)
IS
BEGIN
OPEN o_Rows FOR
select ou.User_id,
ou.AD_Login_ID,
ou.First_name,
ou.Last_Name,
oct.CODE_DESC,
case when ou.deleted is null then 'N'
else 'Y' end Deleted
from tst_ops_users ou, tst_ops_code_tbl oct
where oct.CODE_TYPE ='USER_TYPE'
and oct.code_name = ou.USER_ROLE_TYPE;
END QRY_USERS;
So is there some different syntax with case statements or is there some other erro causing this?
Thanks a bunch for your assistance!!!Which version of the database are you working on? In 8i the PL/SQL engine did not support the use of CASE in SQL statements (along with a whole bunch of other fresh additions to SQL syntax).
If that is your problem you could try this, which ought to use the SQL engine instead...
PROCEDURE QRY_USERS (oRows OUT t_cursor)
IS
BEGIN
OPEN oRows FOR
'select ou.User_id,
ou.AD_Login_ID,
ou.First_name,
ou.Last_Name,
oct.CODE_DESC,
case when ou.deleted is null then ''N''
else ''Y'' end Deleted
from tst_ops_users ou, tst_ops_code_tbl oct
where oct.CODE_TYPE =''USER_TYPE''
and oct.code_name = ou.USER_ROLE_TYPE';
END QRY_USERS;although you can obviate the need for CASE by using either DECODE or NVL2...
nvl2(ou.deleted , 'Y', 'N') AS deletedCheers, APC -
I was wondering how this can be achieved:
I need to do a count of applications by application_type where the "application_recieved_date" >= JAN-2010.
The only issue is that not all applications have a "application_recieved_date", soem are NULL. So i need some sort of rollover date, if this doesnt exist then use another date on the application (application_recieved_date for example), then if this doesnt exist then use another date.
Any help would be great, i have trying decodes and nvl2 functions, but nothing yet.
below is basic query just so you can see names e.t.c, but i really cannot workout the best way of solving this
select application_type, count(*)
from pple_t_application
group by application_type
order by application_type;Hi,
Use COALESCE:
COALESCE (dt1, dt2, dt3, dt4)COALESCE takes 2 or more arguments of the same datatype, and returns the first argument that is not NULL.
I hope this answers your question.
If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only), and the results you want from that data.
Explain how you get those results from that data.
Always say what version of Oracle you're using. -
Add Parameter to hardcoded string in decode function
I have a query something like this :
Select ............
,decode((select bill_sequence_id
from bom_structures_b a
where a.assembly_item_id =POL.ITEM_ID
and a.organization_id=FSP.INVENTORY_ORGANIZATION_ID
and a.alternate_bom_designator is null
and msi.bom_enabled_flag='Y'
),null,null,'test_url'||a.bill_sequence_id) "Destination"
From........
where..........
i want to add the column value that I searched at the end of 'test_url'
If I did decode(...,null,null,'test_url'||222222222) it worked, but when i give bill_sequence_id or a.bill_sequence_id , it cries for invalid identifier.
please assist.
ThanksIts good to flush out your tear glands sometimes.Sure is. I've tried to dechiffer your "query" and to me it looks like something like this:
select <some_columns_we_dont_know_of>
, nvl2(a.bill_sequence_id, 'test_url'|| to_char(a.bill_sequence_id), null) "Destination"
from (select assembly_item_id
, organization_id
from bom_structures_b
where alternate_bom_designator is null) a
, (select pol.item_id
, fsp.inventory_organization_id
from pol
, fsp
, msi
, <other_tables_we_dont_know_of>
where <your_join_conditions>
and msi.bom_enabled_flag='Y'
and <other_predicates>) b
where a.assembly_item_id(+) = b.item_id
and a.organization_id(+) = b.inventory_organization_id;Or perhaps
select <some_columns_we_dont_know_of>
, case
when a.bill_sequence_id is not null and b.bom_enabled_flag = 'Y'
then 'test_url'|| to_char(a.bill_sequence_id)
end "Destination"
from (select assembly_item_id
, organization_id
from bom_structures_b
where alternate_bom_designator is null) a
, (select pol.item_id
, fsp.inventory_organization_id
, msi.bom_enabled_flag
from pol
, fsp
, msi
, <other_tables_we_dont_know_of>
where <your_join_conditions>
and msi.bom_enabled_flag='Y'
and <predicates>) b
where a.assembly_item_id(+) = b.item_id
and a.organization_id(+) = b.inventory_organization_id;Regards
Peter -
Can we decode ObFormLoginCookie using Javascript
So if you want brevity use DECODE, or if you want clarity use CASE.Things can be that simple when dealing with something like this
select case when condition in ('ONE','SIX')
then 1
when condition in ('TWO','TEN')
then 2
else 0
end result
from dual
/* decode counterpart not tested */
select decode(condition,'ONE',1,'SIX',1,'TWO',2,'TEN',2,0) result
from dualbut even a moderate change seems to make brevity vanish too ;) (not to mention dealing with string comparison)
select case when condition in ('ONE','SIX') and date1 > date2 and (amount > limit or limit is null)
then 1
when condition in ('TWO','TEN') and date1 <= date2 and amount <= limit
then 2
else 0
end result
from dual
/* decode counterpart not tested */
select decode(condition,'ONE',decode(sign(date1 - date2,1,nvl2(limit,decode(sign(amount - limit),1,1,0),0),0)),
'SIX',decode(sign(date1 - date2,1,nvl2(limit,decode(sign(amount - limit),1,1,0),0),0)),
'TWO',decode(sign(date2 - date1),1,decode(sign(limit - amount),1,2,0,2,0),0,decode(sign(limit - amount),1,2,0,2,0),0)),
'TEN',decode(sign(date2 - date1),1,decode(sign(limit - amount),1,2,0,2,0),0,decode(sign(limit - amount),1,2,0,2,0),0)),
0
) result
from dualRegards
Etbin -
Hello,
I am new to Oracle. I have a, hopefully basic SQL question.
There is sometime four users in my dbs. But, I would like make query where the users below are returned, even if not in db.
1. Bob
2. Jane
3. John
4. Abul
I have rows in db:
ROWS IN DB
Username account status
bob Support Active
Jane Dev Active
John Dev Expired
How I can write query to find all users, if one is missing. Try to get format
Bob's Support account is active
Jane's Dev account is active
John's Dev account is active
Abul is not in db
I try CASE and Decode, but get bad returns.
Pls help.
Tring to learn SQL. Go to class in three weeks.Hi,
Welcome to the forum!
So you have four special users, each with a name and id number. That sounds like data. Data belongs in tables. You should create a table that has four rows. Then you could use that table to do an outer-join with other tables, such as db.
If you don't have such a table, you can generate a result set on the fly that will serve as a table. The sub-query special_users below is just that:
WITH special_users AS
SELECT 'Abul' AS username FROM dual UNION ALL
SELECT 'BOB' FROM dual UNION ALL
SELECT 'Jane' FROM dual UNION ALL
SELECT 'John' FROM dual
SELECT su.username
|| CASE
WHEN db.username IS NULL
THEN ' is not in db'
ELSE '''s ' || account
|| ' account is '
|| status
END AS msg
FROM special_users su
LEFT OUTER JOIN db ON db.username = su.username
;If you do have a real special_users table, then the main query above works;l just skip the WHERE clause (the forst 7 lines) and, the query is:
SELECT su.username
|| CASE
WHEN db.username IS NULL
THEN ' is not in db'
ELSE '''s ' || account
|| ' account is '
|| status
END AS msg
FROM special_users su
LEFT OUTER JOIN db ON db.username = su.username
;Edited by: Frank Kulash on Sep 28, 2009 3:53 PM
The subject line you chose for this message, "Case, Decode or PlSQL" is very good, and shows the order in which you should try things.
(1) CASE is the general way to handle if-then-else logic in a SQL expression
(2) DECODE (and other specialized features, such as NVL2, which Michaels used) can save you a little typing in special circumstances. Once you have mastered CASE, you can start exploring these other expressions.
(3) PL/SQL is the last resort, used only if there is no good way to do something in SQL. -
Decode statement with ||','||
Hi ,
I've the following requriement where i need to append the 2 numbers with comma inside the decode stmt
create table A_STY_VON ( C_1_ID number ,C_2_ID number ,C_3_ID number)
Insert into A_STY_VON
(C_1_ID, C_2_ID, C_3_ID)
Values
(1, 2, 3);
Insert into A_STY_VON
(C_1_ID, C_3_ID)
Values
(1, 3);
Insert into A_STY_VON
(C_1_ID, C_2_ID)
Values
(1, 2);
Insert into A_STY_VON
(C_2_ID, C_3_ID)
Values
(2, 3);And the following select stmt is working
SELECT DECODE (
A.C_3_ID,
NULL, DECODE (A.C_2_ID,
NULL, A.C_1_ID,
A.C_1_ID || A.C_2_ID) ,
A.C_1_ID
|| A.C_2_ID
|| A.C_3_Id) dcd
FROM A_STY_VON A But i want the comma between the numbers so i tried the following ( with distinct )
where i'm getting the invalid number error
SELECT distinct DECODE (
A.C_3_ID,
NULL, DECODE (A.C_2_ID,
NULL, A.C_1_ID,
A.C_1_ID ||','|| A.C_2_ID) ,
A.C_1_ID
||','|| A.C_2_ID
||','|| A.C_3_Id) dcd
FROM A_STY_VON A Could you please help me to achieve this
Thank you
Edited by: Smile on Apr 26, 2012 3:50 AMJust so you can understand why the problem has happened...
There are some implicit datatype conversions going on in your statement, let's just look at a small part of it...
DECODE (A.C_2_ID,
NULL, A.C_1_ID,
A.C_1_ID || A.C_2_ID)Your ID's are numeric.
DECODE as a function can only return a single datatype. That datatype is determined by the datatype of the first value to be returned (if it's null that's another issue but let's not go there).
So, in your above statement the datatype returned by DECODE is determined by A.C_1_ID, which is numeric.
Also in your above statement you are doing a string concatenation of A.C_1_ID and A.C_2_ID, so those numbers are implicitly converted to strings and concatenated, but then because DECODE is now defined as needing a number to be returned, the concatenated string of numbers are implicitly converted back to a number, which is fine because the whole string is numeric.
In PL/SQL code this would go along these principles...
... function ...
declare
v_retval NUMBER;
v_c_1_id NUMBER := 123;
v_c_2_id NUMBER := 234;
begin
if v_c_2_id is null then
v_retval := v_c_1_id;
else
v_retval := to_number(to_char(v_c_1_id)||to_char(v_c_2_id));
end if;
return v_retval;
end;Now, if you try and put a comma into your concatenation...
DECODE (A.C_2_ID,
NULL, A.C_1_ID,
A.C_1_ID ||','|| A.C_2_ID)Still the first value returned has defined the DECODE as needing to return a numeric value, but this time the second returned value (The 'else' part of the decode) has a string containing numeric digits with a comma in between. When it implicitly tries to convert this string to a number so it can be returned from the function, it finds that it's not a valid number.
And we can see this if we use the same PL/SQL type code...
SQL> declare
2 v_retval NUMBER;
3 v_c_1_id NUMBER := 123;
4 v_c_2_id NUMBER := 234;
5 begin
6 if v_c_2_id is null then
7 v_retval := v_c_1_id;
8 else
9 v_retval := to_number(to_char(v_c_1_id)||','||to_char(v_c_2_id));
10 end if;
11 --return v_retval;
12 end;
13 /
declare
ERROR at line 1:
ORA-06502: PL/SQL: numeric or value error: character to number conversion error
ORA-06512: at line 9It can't do the to_number on the string when it expects the return value to be numeric.
SQL has a nice NVL2 function (http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions106.htm) which you can use instead when trying to determine different output based on one of the values being null...
SQL> ed
Wrote file afiedt.buf
1 with a as (select 123 as c_1_id, 234 as c_2_id from dual union all
2 select 789, null from dual)
3 --
4 -- end of test data
5 --
6 select c_1_id, c_2_id,
7 nvl2(c_2_id,c_1_id||','||c_2_id,c_1_id) as result
8* from a
SQL> /
C_1_ID C_2_ID RESULT
123 234 123,234
789 789Again, this is using implicit datatype conversion and the resultant datatype of NVL2 is determined by the first result (the second parameter) just as with decode, but because of the way it works, the first result is what it should do if the passed in first parameter is not null and therefore you can force the implicit conversion to a string datatype that way. -
Emulate nvl2() ?
I have a procedure that uses the nvl2() function of ORACLE 8.15 that I need to create in a 8.0.5 database. Is it possible to emulate the nvl2() function somewhoe differently? (e.g. via nvl() or decode() ?)
Something like this what you are wanting?
SQL> variable v_test varchar2
SQL> select decode(:v_test, null, 'null', 'not null') result from dual;
RESULT
null
1 row selected.
SQL> exec :v_test := 'a';
PL/SQL procedure successfully completed.
select decode(:v_test, null, 'null', 'not null') result from dual;
RESULT
not null
1 row selected.
SQL>You could wrap that in a function or procedure to do what you want I think...
- Mark -
Logical Operations in SQL decode function ?
Hi,
Is it possible to do Logical Operations in SQL decode function
like
'>'
'<'
'>='
'<='
'<>'
not in
in
not null
is null
eg...
select col1 ,order_by,decode ( col1 , > 10 , 0 , 1)
from tab;
select col1 ,order_by,decode ( col1 , <> 10 , 0 , 1)
from tab;
select col1 ,order_by,decode ( col1 , not in (10,11,12) , 0 , 1)
from tab;
select col1 ,order_by,decode ( col1 ,is null , 0 , 1)
from tab;
Regards,
infan
Edited by: user780731 on Apr 30, 2009 12:07 AM
Edited by: user780731 on Apr 30, 2009 12:07 AM
Edited by: user780731 on Apr 30, 2009 12:08 AM
Edited by: user780731 on Apr 30, 2009 12:08 AM
Edited by: user780731 on Apr 30, 2009 12:09 AMexample:
select col1 ,order_by,case when col1 > 10 then 0 else 1 end
from tab;
select col1 ,order_by,case when col1 <> 10 then 0 else 1 end
from tab;
select col1 ,order_by,case when col1 not in (10,11,12) then 0 else 1 end
from tab;As for testing for null, decode handles that by default anyway so you can have decode or case easily..
select col1 ,order_by,decode (col1, null , 0 , 1)
from tab;
select col1 ,order_by,case when col1 is null then 0 else 1 end
from tab; -
USING NULL AND SELECT ALL IN DECODE
COL1 has the following values:
COL1
====
A
B
C
A
B
C
A
D
D
SELECT COL1 FROM TABLE1 WHERE COL1 =
DECODE(:VAL1, 'A', 'AA', 'B', 'BB', 'C', 'CC', 'D', 'DD')
1. what about the null values ? how can I add to the above statements when I enter null for the parameter :VAL1
2. what about all the values in COL1, what shall I enter for :VAL1 ?
THANKS.SELECT COL1 FROM TABLE1
WHERE nvl(COL1,0) = DECODE(:VAL1, 'A', 'AA', 'B', 'BB', 'C', 'CC', 'D', 'DD',null,0)
Can we use in this way?
Shishu Paul
Chandigarh-India -
Clearing values from request in decode method
I am using a custom table paginator. In its decode method I have the next code to control whether next link is clicked:
String pLink = (String)requestMap.get("pLink" + clientId);
if ((pLink != null) && (!pLink.equals(""))) {
if (pLink.equals("next")) {
} else if (pLink.equals("previous")) {
}But the next sequence produces some problems:
1. Initial page load.
2. Click on next link.
3. Table navigates ok to next page.
4. Reload page (push F5).
5. The previous click still remains in the request, so decode method think next link is pressed again.
6. Application abnormal behaviour arises.
So, I am trying to clear the next_link key from the request, but next code throws an UnsupportedOperationException:
String pLink = (String)requestMap.get("pLink" + clientId);
if ((pLink != null) && (!pLink.equals(""))) {
if (pLink.equals("next")) {
} else if (pLink.equals("previous")) {
requestMap.put("pLink" + clientId, "");
}Do any of you have some ideas?Hey, where are you RaymondDeCampo, rLubke, BalusC ... the masters of JSF Universe?
;-) -
This works on WinXP but not Linux. Why? It takes the first frame of an animated gif and writes a thumbnail.
GifDecoder d = new GifDecoder();
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
log.debug("reading gif");
d.read(bis);
log.debug("reading framecount");
int n = d.getFrameCount();
log.debug("read framecount" + n);
for (int i = 0; i < 1; i++) {
BufferedImage frame = d.getFrame(i); // frame i
int t = d.getDelay(i); // display duration of frame in milliseconds
log.debug("resizing frame");
File gifoutputfile = new File("gif" + i + outputthumbFilename);
BufferedImage bdest = new BufferedImage(60, 60, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bdest.createGraphics();
AffineTransform at = AffineTransform.getScaleInstance((double) 60 / frame.getWidth(), (double) 60 / frame.getHeight());
g.drawRenderedImage(frame, at);
ImageIO.setUseCache(false);
ImageIO.write(bdest, "GIF", new File(outputthumbFilename));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
* Class GifDecoder - Decodes a GIF file into one or more frames. <br>
* <pre>
* Example:
* GifDecoder d = new GifDecoder();
* d.read("sample.gif");
* int n = d.getFrameCount();
* for (int i = 0; i < n; i++) {
* BufferedImage frame = d.getFrame(i); // frame i
* int t = d.getDelay(i); // display duration of frame in milliseconds
* // do something with frame
* </pre>
* No copyright asserted on the source code of this class. May be used for any
* purpose, however, refer to the Unisys LZW patent for any additional
* restrictions. Please forward any corrections to [email protected].
* @author Kevin Weiner, FM Software; LZW decoder adapted from John Cristy's
* ImageMagick.
* @version 1.03 November 2003
public class GifDecoder {
* File read status: No errors.
public static final int STATUS_OK = 0;
* File read status: Error decoding file (may be partially decoded)
public static final int STATUS_FORMAT_ERROR = 1;
* File read status: Unable to open source.
public static final int STATUS_OPEN_ERROR = 2;
protected BufferedInputStream in;
protected int status;
protected int width; // full image width
protected int height; // full image height
protected boolean gctFlag; // global color table used
protected int gctSize; // size of global color table
protected int loopCount = 1; // iterations; 0 = repeat forever
protected int[] gct; // global color table
protected int[] lct; // local color table
protected int[] act; // active color table
protected int bgIndex; // background color index
protected int bgColor; // background color
protected int lastBgColor; // previous bg color
protected int pixelAspect; // pixel aspect ratio
protected boolean lctFlag; // local color table flag
protected boolean interlace; // interlace flag
protected int lctSize; // local color table size
protected int ix, iy, iw, ih; // current image rectangle
protected Rectangle lastRect; // last image rect
protected BufferedImage image; // current frame
protected BufferedImage lastImage; // previous frame
protected byte[] block = new byte[256]; // current data block
protected int blockSize = 0; // block size
// last graphic control extension info
protected int dispose = 0;
// 0=no action; 1=leave in place; 2=restore to bg; 3=restore to prev
protected int lastDispose = 0;
protected boolean transparency = false; // use transparent color
protected int delay = 0; // delay in milliseconds
protected int transIndex; // transparent color index
protected static final int MaxStackSize = 4096;
// max decoder pixel stack size
// LZW decoder working arrays
protected short[] prefix;
protected byte[] suffix;
protected byte[] pixelStack;
protected byte[] pixels;
protected ArrayList frames; // frames read from current file
protected int frameCount;
static class GifFrame {
public GifFrame(BufferedImage im, int del) {
image = im;
delay = del;
public BufferedImage image;
public int delay;
* Gets display duration for specified frame.
* @param n
* int index of frame
* @return delay in milliseconds
public int getDelay(int n) {
delay = -1;
if ((n >= 0) && (n < frameCount)) {
delay = ((GifFrame) frames.get(n)).delay;
return delay;
* Gets the number of frames read from file.
* @return frame count
public int getFrameCount() {
return frameCount;
* Gets the first (or only) image read.
* @return BufferedImage containing first frame, or null if none.
public BufferedImage getImage() {
return getFrame(0);
* Gets the "Netscape" iteration count, if any. A count of 0 means repeat
* indefinitiely.
* @return iteration count if one was specified, else 1.
public int getLoopCount() {
return loopCount;
* Creates new frame image from current data (and previous frames as specified
* by their disposition codes).
protected void setPixels() {
// expose destination image's pixels as int array
int[] dest = ((DataBufferInt) image.getRaster().getDataBuffer()).getData();
// fill in starting image contents based on last image's dispose code
if (lastDispose > 0) {
if (lastDispose == 3) {
// use image before last
int n = frameCount - 2;
if (n > 0) {
lastImage = getFrame(n - 1);
} else {
lastImage = null;
if (lastImage != null) {
int[] prev = ((DataBufferInt) lastImage.getRaster().getDataBuffer()).getData();
System.arraycopy(prev, 0, dest, 0, width * height);
// copy pixels
if (lastDispose == 2) {
// fill last image rect area with background color
Graphics2D g = image.createGraphics();
Color c = null;
if (transparency) {
c = new Color(0, 0, 0, 0); // assume background is transparent
} else {
c = new Color(lastBgColor); // use given background color
g.setColor(c);
g.setComposite(AlphaComposite.Src); // replace area
g.fill(lastRect);
g.dispose();
// copy each source line to the appropriate place in the destination
int pass = 1;
int inc = 8;
int iline = 0;
for (int i = 0; i < ih; i++) {
int line = i;
if (interlace) {
if (iline >= ih) {
pass++;
switch (pass) {
case 2:
iline = 4;
break;
case 3:
iline = 2;
inc = 4;
break;
case 4:
iline = 1;
inc = 2;
line = iline;
iline += inc;
line += iy;
if (line < height) {
int k = line * width;
int dx = k + ix; // start of line in dest
int dlim = dx + iw; // end of dest line
if ((k + width) < dlim) {
dlim = k + width; // past dest edge
int sx = i * iw; // start of line in source
while (dx < dlim) {
// map color and insert in destination
int index = ((int) pixels[sx++]) & 0xff;
int c = act[index];
if (c != 0) {
dest[dx] = c;
dx++;
* Gets the image contents of frame n.
* @return BufferedImage representation of frame, or null if n is invalid.
public BufferedImage getFrame(int n) {
BufferedImage im = null;
if ((n >= 0) && (n < frameCount)) {
im = ((GifFrame) frames.get(n)).image;
return im;
* Gets image size.
* @return GIF image dimensions
public Dimension getFrameSize() {
return new Dimension(width, height);
* Reads GIF image from stream
* @param BufferedInputStream
* containing GIF file.
* @return read status code (0 = no errors)
public int read(BufferedInputStream is) {
init();
if (is != null) {
in = is;
readHeader();
if (!err()) {
readContents();
if (frameCount < 0) {
status = STATUS_FORMAT_ERROR;
} else {
status = STATUS_OPEN_ERROR;
try {
is.close();
} catch (IOException e) {
return status;
* Reads GIF image from stream
* @param InputStream
* containing GIF file.
* @return read status code (0 = no errors)
public int read(InputStream is) {
init();
if (is != null) {
if (!(is instanceof BufferedInputStream))
is = new BufferedInputStream(is);
in = (BufferedInputStream) is;
readHeader();
if (!err()) {
readContents();
if (frameCount < 0) {
status = STATUS_FORMAT_ERROR;
} else {
status = STATUS_OPEN_ERROR;
try {
is.close();
} catch (IOException e) {
return status;
* Reads GIF file from specified file/URL source (URL assumed if name contains
* ":/" or "file:")
* @param name
* String containing source
* @return read status code (0 = no errors)
public int read(String name) {
status = STATUS_OK;
try {
name = name.trim().toLowerCase();
if ((name.indexOf("file:") >= 0) || (name.indexOf(":/") > 0)) {
URL url = new URL(name);
in = new BufferedInputStream(url.openStream());
} else {
in = new BufferedInputStream(new FileInputStream(name));
status = read(in);
} catch (IOException e) {
status = STATUS_OPEN_ERROR;
return status;
* Decodes LZW image data into pixel array. Adapted from John Cristy's
* ImageMagick.
protected void decodeImageData() {
int NullCode = -1;
int npix = iw * ih;
int available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, count, i, datum, data_size, first, top, bi, pi;
if ((pixels == null) || (pixels.length < npix)) {
pixels = new byte[npix]; // allocate new pixel array
if (prefix == null)
prefix = new short[MaxStackSize];
if (suffix == null)
suffix = new byte[MaxStackSize];
if (pixelStack == null)
pixelStack = new byte[MaxStackSize + 1];
// Initialize GIF data stream decoder.
data_size = read();
clear = 1 << data_size;
end_of_information = clear + 1;
available = clear + 2;
old_code = NullCode;
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
for (code = 0; code < clear; code++) {
prefix[code] = 0;
suffix[code] = (byte) code;
// Decode GIF pixel stream.
datum = bits = count = first = top = pi = bi = 0;
for (i = 0; i < npix;) {
if (top == 0) {
if (bits < code_size) {
// Load bytes until there are enough bits for a code.
if (count == 0) {
// Read a new data block.
count = readBlock();
if (count <= 0)
break;
bi = 0;
datum += (((int) block[bi]) & 0xff) << bits;
bits += 8;
bi++;
count--;
continue;
// Get the next code.
code = datum & code_mask;
datum >>= code_size;
bits -= code_size;
// Interpret the code
if ((code > available) || (code == end_of_information))
break;
if (code == clear) {
// Reset decoder.
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
available = clear + 2;
old_code = NullCode;
continue;
if (old_code == NullCode) {
pixelStack[top++] = suffix[code];
old_code = code;
first = code;
continue;
in_code = code;
if (code == available) {
pixelStack[top++] = (byte) first;
code = old_code;
while (code > clear) {
pixelStack[top++] = suffix[code];
code = prefix[code];
first = ((int) suffix[code]) & 0xff;
// Add a new string to the string table,
if (available >= MaxStackSize)
break;
pixelStack[top++] = (byte) first;
prefix[available] = (short) old_code;
suffix[available] = (byte) first;
available++;
if (((available & code_mask) == 0) && (available < MaxStackSize)) {
code_size++;
code_mask += available;
old_code = in_code;
// Pop a pixel off the pixel stack.
top--;
pixels[pi++] = pixelStack[top];
i++;
for (i = pi; i < npix; i++) {
pixels[i] = 0; // clear missing pixels
* Returns true if an error was encountered during reading/decoding
protected boolean err() {
return status != STATUS_OK;
* Initializes or re-initializes reader
protected void init() {
status = STATUS_OK;
frameCount = 0;
frames = new ArrayList();
gct = null;
lct = null;
* Reads a single byte from the input stream.
protected int read() {
int curByte = 0;
try {
curByte = in.read();
} catch (IOException e) {
status = STATUS_FORMAT_ERROR;
return curByte;
* Reads next variable length block from input.
* @return number of bytes stored in "buffer"
protected int readBlock() {
blockSize = read();
int n = 0;
if (blockSize > 0) {
try {
int count = 0;
while (n < blockSize) {
count = in.read(block, n, blockSize - n);
if (count == -1)
break;
n += count;
} catch (IOException e) {
if (n < blockSize) {
status = STATUS_FORMAT_ERROR;
return n;
* Reads color table as 256 RGB integer values
* @param ncolors
* int number of colors to read
* @return int array containing 256 colors (packed ARGB with full alpha)
protected int[] readColorTable(int ncolors) {
int nbytes = 3 * ncolors;
int[] tab = null;
byte[] c = new byte[nbytes];
int n = 0;
try {
n = in.read(c);
} catch (IOException e) {
if (n < nbytes) {
status = STATUS_FORMAT_ERROR;
} else {
tab = new int[256]; // max size to avoid bounds checks
int i = 0;
int j = 0;
while (i < ncolors) {
int r = ((int) c[j++]) & 0xff;
int g = ((int) c[j++]) & 0xff;
int b = ((int) c[j++]) & 0xff;
tab[i++] = 0xff000000 | (r << 16) | (g << 8) | b;
return tab;
* Main file parser. Reads GIF content blocks.
protected void readContents() {
// read GIF file content blocks
boolean done = false;
while (!(done || err())) {
int code = read();
switch (code) {
case 0x2C: // image separator
readImage();
break;
case 0x21: // extension
code = read();
switch (code) {
case 0xf9: // graphics control extension
readGraphicControlExt();
break;
case 0xff: // application extension
readBlock();
String app = "";
for (int i = 0; i < 11; i++) {
app += (char) block;
if (app.equals("NETSCAPE2.0")) {
readNetscapeExt();
} else
skip(); // don't care
break;
default: // uninteresting extension
skip();
break;
case 0x3b: // terminator
done = true;
break;
case 0x00: // bad byte, but keep going and see what happens
break;
default:
status = STATUS_FORMAT_ERROR;
* Reads Graphics Control Extension values
protected void readGraphicControlExt() {
read(); // block size
int packed = read(); // packed fields
dispose = (packed & 0x1c) >> 2; // disposal method
if (dispose == 0) {
dispose = 1; // elect to keep old image if discretionary
transparency = (packed & 1) != 0;
delay = readShort() * 10; // delay in milliseconds
transIndex = read(); // transparent color index
read(); // block terminator
* Reads GIF file header information.
protected void readHeader() {
String id = "";
for (int i = 0; i < 6; i++) {
id += (char) read();
if (!id.startsWith("GIF")) {
status = STATUS_FORMAT_ERROR;
return;
readLSD();
if (gctFlag && !err()) {
gct = readColorTable(gctSize);
bgColor = gct[bgIndex];
* Reads next frame image
protected void readImage() {
ix = readShort(); // (sub)image position & size
iy = readShort();
iw = readShort();
ih = readShort();
int packed = read();
lctFlag = (packed & 0x80) != 0; // 1 - local color table flag
interlace = (packed & 0x40) != 0; // 2 - interlace flag
// 3 - sort flag
// 4-5 - reserved
lctSize = 2 << (packed & 7); // 6-8 - local color table size
if (lctFlag) {
lct = readColorTable(lctSize); // read table
act = lct; // make local table active
} else {
act = gct; // make global table active
if (bgIndex == transIndex)
bgColor = 0;
int save = 0;
if (transparency) {
save = act[transIndex];
act[transIndex] = 0; // set transparent color if specified
if (act == null) {
status = STATUS_FORMAT_ERROR; // no color table defined
if (err())
return;
decodeImageData(); // decode pixel data
skip();
if (err())
return;
frameCount++;
// create new image to receive frame data
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
setPixels(); // transfer pixel data to image
frames.add(new GifFrame(image, delay)); // add image to frame list
if (transparency) {
act[transIndex] = save;
resetFrame();
* Reads Logical Screen Descriptor
protected void readLSD() {
// logical screen size
width = readShort();
height = readShort();
// packed fields
int packed = read();
gctFlag = (packed & 0x80) != 0; // 1 : global color table flag
// 2-4 : color resolution
// 5 : gct sort flag
gctSize = 2 << (packed & 7); // 6-8 : gct size
bgIndex = read(); // background color index
pixelAspect = read(); // pixel aspect ratio
* Reads Netscape extenstion to obtain iteration count
protected void readNetscapeExt() {
do {
readBlock();
if (block[0] == 1) {
// loop count sub-block
int b1 = ((int) block[1]) & 0xff;
int b2 = ((int) block[2]) & 0xff;
loopCount = (b2 << 8) | b1;
} while ((blockSize > 0) && !err());
* Reads next 16-bit value, LSB first
protected int readShort() {
// read 16-bit value, LSB first
return read() | (read() << 8);
* Resets frame state for reading next image.
protected void resetFrame() {
lastDispose = dispose;
lastRect = new Rectangle(ix, iy, iw, ih);
lastImage = image;
lastBgColor = bgColor;
int dispose = 0;
boolean transparency = false;
int delay = 0;
lct = null;
* Skips variable length blocks up to and including next zero length block.
protected void skip() {
do {
readBlock();
} while ((blockSize > 0) && !err());
Niklas wrote:
This works on WinXP but not Linux. Why? Please don't just post reams of code without providing more context and information.
How is it failing on Linux? Wrong results? What are they? Error messages? What do they say? You need to give us some place to start looking. -
Who can decode this who ever can I will give 4 dukes cause thats all i have
who ever is the first to decode this and tell me what it says I will give you 4 duke dollars since that is all I have here it is
vs.vo.~seeing something
vszz}.vss
Maybe you are looking for
-
Poor image quality in v5.5
Below is a copy of a slide and highlighted in red is an image I have copied (using Snagit), saved as .png and imported via Captivate v.5.5 onto the slide. As you can see the quality of the text in "edit" view is very very poor - yet this same image l
-
Changing a portal user's password programatically
Hi, I'm attempting to reset a user's password, and so far i got it to work once using: update wwsec_person$ set password = wwsso_utl.hash_pwd('PASSWORD') where user_name='USER' after running that statement and committing, the password seemed to chang
-
How can I remove *standalone="yes"* and include xmlns:xsd and xsi in root
Using JAXB 2.1 for the first time. Was wondering how I would remove standalone="yes" from <?xml version="1.0" encoding="UTF-8" standalone="yes" ?> And also how can I add xmlns:xsd="http://www.w3.org/2001/XMLSchema" and to the root element xmlns:xsi="
-
I have an older Bose Ipod system that the Older Ipods plug into to play and charge. I bought an Ipod touch and now I get a message telling me charging is not supported. Is there and adapter that will allow the two pieces to plug togerther, and work?
-
Sorry first post in this forum. I can log on to Yahoo email, read a few emails and then the infamous multi-colored spinning wheel appears and I end up having to shut down and cycle back in again. I have a 2011 MacBookPro 17 not quite a year and it