DBMS_LOB.GETLENGTH into bytes
I am using Oralce 11.2.0.3. I am using DBMS_LOB.GETLENGTH to determine size of the CLOB . Is the value given by DBMS_LOB.GETLENGTH in bytes?
For WE8MSWIN1252 you can try directly running LENGTHB against the CLOB. LENGTHB won't work against multibyte LOBs (in which case you will have to use a function similar to the above). But if it does run then you know your CLOB is single-byte and you get the size as well.
SQL> select lengthb(c) from z_t;
LENGTHB(C)
4343
4343
4969
5414
4593
162
6 rows selected
SQL> select lengthb(nc) from z_t;
select lengthb(nc) from z_t
ORA-22998: CLOB or NCLOB in multibyte character set not supported
SQL> select clob_lengthb(nc) from z_t;
CLOB_LENGTHB(NC)
4343
4343
4969
5414
4593
162
6 rows selected
Similar Messages
-
DBMS_LOB.GETLENGTH Bytes? K? MB? GB?
What is size of a BLOB or LOB returned with DBMS_LOB.GETLENGTH? Is it bytes? K? MB?
http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_lob.htm#sthref3763
GETLENGTH Functions
This function gets the length of the specified LOB. The length in bytes or characters is returned. -
Dbms_lob.getlength() returns different source and destination lengths
I am fairly new to PL/SQL so maybe this is an obvious problem but here goes. I am updating a clob field with a text file ~5KB in size. The field updates fine (as far as I can tell). Before I update the field, I open the source file as a bfile and then inquire the length using dbms_lob.getlength(). I then update the clob field using dbms_lob.loadclobfromfile(). This seems to work fine. However, when I use dbms_lob.getlength() on the destination object returned by dbms_lob.loadclobfromfile(), I get a length 3 characters less than then the source object (5072 vs 5075). Both the source and destination offsets are set to 1.
Probing on what documentation I could find, I found this at http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28419/d_lob.htm#i998484:
"The length returned for a BFILE includes the EOF, if it exists. Any 0-byte or space filler in the LOB caused by previous ERASE or WRITE operations is also included in the length count. The length of an empty internal LOB is 0."
I did not create the source file and I believe it is a Unix type file (because of the lack of CRs) and I am running on Windows 7. I am also using 11g Express. Could the use of a Unix-type file for a CLOB on a Windows system be causing this character count difference?
Once I found this issue I can work around it. I just want to understand what is going on.
Thanks to all who look at this.The EOF and the LF versus CR/LF could influence the count difference, yes.
Another explain could possibly be character set conversions. The BFILE I believe counts bytes, a CLOB would count "characters" - so if the source happens to contain a few multibyte characters (UTF), then the byte count would be larger than the character count.
To help you find the cause for your exact file, then I can suggest a couple of things you might do to explore the issue:
<li>Load the file into a BLOB instead of a CLOB and see what getlength() returns for the BLOB. BLOBs would also do byte counts and not try to treat the source as text.
<li>Save the CLOB back into the filesystem and compare the original file with the exported CLOB and check the differences with some filecompare tool. -
Dbms_lob.getlength() returns different values
Hi !
I am not a developer.. So, possibly cannot answer developer specific question.
We have two instances running on 10.2.0.4 but both giving different value for
declare
xml varchar2(32676) :=
'SELECT XT_STRATEGY, ACCT_DESCRIPTION,sum(MON_PL) PL_MON ,sum(TUE_PL) PL_TUE,sum(WED_PL) PL_WED ,sum(THU_PL) PL_THU, sum(FRI_PL) PL_FRI, sum(WTD_PL) PL_WTDPL,sum(WTD_PREMIUM_PL) PL_WTDPRMPL, sum(MTD_PL) PL_MARKPL,sum(MTD_PREMIUM_PL) PL_MTDPRMPL,sum(YTD_PL) PL_YTDPL,sum(YTD_PREMIUM_PL) PL_YTDPRMPL,
DLC_REGION,DLC_ENTITY FROM (SELECT xt_strategy, acct_description ,case when blankout_date < to_char( to_date( fv[EOD] )+ (1 -to_char(to_date(to_date( fv[EOD] )),''D''))) then 0 else MON_PL end as MON_PL, case when blankout_date < to_char( to_date( fv[EOD] )+ (1 -to_char(to_date(to_date( fv[EOD] )),''D''))) then 0 else tue_pl end as tue_pl,
case when blankout_date < to_char( to_date( fv[EOD] )+ (1 -to_char(to_date(to_date( fv[EOD] )),''D''))) then 0 else WED_PL end as WED_PL, case when blankout_date < to_char( to_date( fv[EOD] )+ (1 -to_char(to_date(to_date( fv[EOD] )),''D''))) then 0 else THU_PL end as THU_PL,
case when blankout_date < to_char( to_date( fv[EOD] )+ (1 -to_char(to_date(to_date( fv[EOD] )),''D''))) then 0 else FRI_PL end as FRI_PL, case when blankout_date < to_char( to_date( fv[EOD] )+ (1 -to_char(to_date(to_date( fv[EOD] )),''D''))) then 0 else WTD_PL end as WTD_PL,
case when blankout_date < to_char( to_date( fv[EOD] )+ (1 -to_char(to_date(to_date( fv[EOD] )),''D''))) then 0 else WTD_PREMIUM_PL end as WTD_PREMIUM_PL,
case when blankout_date < (select actual_date from tbl_date where date_type = ''PLMonthStart'' and to_char(actual_date, ''MMYYYY'') = to_char(to_date( fv[EOD] ),''MMYYYY'')) then 0 else mtd_pl end as mtd_pl,
case when blankout_date < (select actual_date from tbl_date where date_type = ''PLMonthStart'' and to_char(actual_date, ''MMYYYY'') = to_char(to_date( fv[EOD] ),''MMYYYY'')) then 0 else MTD_PREMIUM_PL end as MTD_PREMIUM_PL,
case when blankout_date < (select to_date(''01-JAN-''|| to_char(to_date((fv[EOD]),''DD-MON-YYYY''),''YYYY''),''DD-MON-YYYY'') from tbl_business_date) then 0 else ytd_PL end as ytd_PL,
case when blankout_date < (select to_date(''01-JAN-''|| to_char(to_date((fv[EOD]),''DD-MON-YYYY''),''YYYY''),''DD-MON-YYYY'') from tbl_business_date) then 0 else ytd_premium_PL end as ytd_premium_PL,
IN_STRIKECURR, IN_QUOTEDCUR, case dlc_region when ''LON'' then ''LN'' when ''NYC'' then ''NY'' when ''TOK'' then ''TK'' else dlc_region
end as DLC_REGION, DLC_ENTITY,DTL_REFERENCE,TRADE_STATE,blankout_date
FROM (select a.bo_book_id as xt_strategy, a.bo_book_id as acct_description , b.mon_pl, b.tue_pl, b.wed_pl,b.thu_pl,b.fri_pl,b.wtd_pl, b.wtd_premium_pl , b.mtd_pl , b.mtd_premium_pl, b.ytd_pl, b.ytd_premium_pl,
a.BASE_CCY as IN_STRIKECURR, A.QUOTED_CCY AS IN_QUOTEDCUR, a.region_code as dlc_region, a.entity_acronym as dlc_entity, TP.EBI_TRADE_ID AS DTL_REFERENCE, a.trade_state,
case when a.trade_state in (7,8,13) then a.amendment_date when a.maturity_date > nvl(a.premium_settlement_date, to_date(''01-JAN-1900'')) then
Case when a.trade_state in (4,5 ) then trunc(a.updated_date) else a.maturity_date end else a.premium_settlement_date end as blankout_date FROM TBL_TRADE_HIST A
join vw_feed_downstream_trade_id tp on a.trade_id = tp.trade_id and tp.mapping_source_name = ''ramfx''
join tbl_pl b on a.trade_id = b.trade_id and a.version = b.trade_version and b.pl_date = (select max(pl_date) from tbl_pl d where a.trade_id = d.trade_id and pl_date <= fv[EOD] )
join tbl_bo_book bk on a.bo_book_id = bk.bo_book_id and bk.business_Area = ''OPTIONS''
where b.pl_date < fv[EOD]
AND NOT EXISTS (SELECT 1 FROM TBL_EOD_TRADES D WHERE A.TRADE_ID = D.TRADE_ID AND D.BUSINESS_DATE = fv[EOD] )
UNION
SELECT A.XT_STRATEGY, A.ACCT_DESCRIPTION, C.MON_PL,C.TUE_PL, C.WED_PL,C.THU_PL, C.FRI_PL,C.WTD_PL,C.WTD_PREMIUM_PL,C.MTD_PL,C.MTD_PREMIUM_PL,C.YTD_PL,C.YTD_PREMIUM_PL,
A.IN_STRIKECURR, A.IN_QUOTEDCUR, A.DLC_REGION,A.DLC_ENTITY, A.DTL_REFERENCE , a.trade_state , case when a.trade_state in (7,8,13) then a.DLC_BUSDATEUPD when a.IN_EXPIRATION > nvl(a.XT_SETTLEDATE, to_date(''01-JAN-1900'')) then a.IN_EXPIRATION else a.XT_SETTLEDATE end as blankout_date
FROM VW_EBI_FEED A , TBL_EOD_TRADES B , TBL_PL C
WHERE A.TRADE_ID = B.TRADE_ID AND A.VERSION = B.TRADE_VERSION AND A.TRADE_ID = C.TRADE_ID
AND A.ACCT_RISKFEED = ''D'' AND A.DLC_DEALSTATE in (''LIVE'',''PENDING'',''CANCELLED'',''REVERSED'') AND A.VERSION = C.TRADE_VERSION
AND B.BUSINESS_DATE = to_date( fv[EOD] ,''DD-MON-YYYY'') AND C.PL_DATE = to_date( fv[EOD] ,''DD-MON-YYYY'')
UNION
SELECT A.BO_BOOK_ID AS XT_STRATEGY , A.BO_BOOK_ID AS ACCT_DESCRIPTION, a.MON_PL , a.TUE_PL , a.WED_PL, a.THU_PL , a.FRI_PL, a.WTD_PL ,a.WTD_PREMIUM_PL , a.mtd_pl, a.MTD_PREMIUM_PL,a.ytd_PL , a.ytd_premium_PL,A.BASE_CCY AS IN_STRIKECURR,A.QUOTED_CCY AS IN_QUOTEDCUR,
A.REGION_CODE as dlc_region ,A.ENTITY_ACRONYM AS DLC_ENTITY, A.MAPPING_SOURCE_ID AS DTL_REFERENCE, 12 as trade_state , a.PL_DATE as blankout_date
FROM TBL_PL_ARCH A , tbl_bo_book b where a.bo_book_id = b.bo_book_id and b.business_area = ''OPTIONS''
union
select d.bo_book_id as xt_strategy, d.bo_book_id as acct_description, case when to_char(b.pl_date,''D'') = 6 then (b.inception_pl + b.inception_premium_pl ) else (b.mon_pl * -1) end as mon_pl ,
case when to_char(b.pl_date,''D'') = 2 then (b.inception_pl + b.inception_premium_pl ) when to_char(b.pl_date,''D'') > 2 then (b.tue_PL * -1) else 0 end as tue_pl, case when to_char(b.pl_date,''D'') = 3 then (b.inception_pl + b.inception_premium_pl ) when to_char(b.pl_date,''D'') > 3 then (b.wed_pl * -1) else 0 end as wed_pl ,
case when to_char(b.pl_date,''D'') = 4 then (b.inception_pl + b.inception_premium_pl) when to_char(b.pl_date,''D'') > 4 then (b.thu_pl * -1) else 0 end as thu_pl ,case when to_char(b.pl_date,''D'') = 5 then (b.inception_pl + b.inception_premium_pl) when to_char(b.pl_date,''D'') > 5 then (b.fri_pl * -1) else 0 end as fri_pl ,
(b.mon_pl + b.tue_pl + b.wed_pl + b.thu_pl + b.fri_pl) * -1 + (b.inception_pl + b.inception_premium_pl) as wtd_pl, case when b.wtd_premium_pl <> 0 then b.wtd_premium_pl *-1 + (b.inception_premium_pl) else b.wtd_premium_pl end as wtd_premium_pl , case when b.mtd_pl <> 0 then b.mtd_pl * -1 + (b.inception_pl) else b.mtd_pl end as mtd_pl ,
case when b.mtd_premium_pl <> 0 then b.mtd_premium_pl * -1 + (b.inception_premium_pl ) else b.mtd_premium_pl end as mtd_premium_pl, case when b.ytd_pl <> 0 then b.ytd_pl * -1 + (b.inception_pl) else b.ytd_pl end as ytd_pl,
case when b.ytd_premium_pl <> 0 then b.ytd_premium_pl * -1 + (b.inception_premium_pl) else b.ytd_premium_pl end as ytd_premium_pl ,
c.base_ccy as IN_STRIKECURR,c.quoted_ccy as IN_QUOTEDCUR,c.region_code as dlc_region,c.entity_acronym as dlc_entity, to_char(c.trade_id) as dtl_reference,
8 as trade_state, case when to_char(b.pl_date,''D'') = 6 then b.pl_date + 2 else b.pl_date end as blankout_date
from tbl_trade_hist a
join tbl_pl b on a.trade_id = b.trade_id and a.version = b.trade_version
join tbl_trade_hist c on a.tradE_id = c.trade_id
join tbl_pl d on c.trade_id = d.trade_id and c.version = d.trade_version and d.pl_date = (select max(e.pl_date) from tbl_pl e where c.trade_id = e.trade_id and e.pl_date <= c.amendment_date)
join tbl_bo_book f on a.bo_book_id = f.bo_book_id and f.business_area = ''OPTIONS''
where (b.bo_book_id <> d.bo_book_id or a.region_code <> c.region_code or a.entity_acronym <> c.entity_acronym or a.base_ccy <> c.base_ccy or a.quoted_ccy <> c.quoted_ccy)
and d.pl_date - b.pl_date = case when to_char(d.pl_date,''DAY'') = ''MON'' then 3 else 1 end
and d.pl_date <= to_date( fv[EOD] ,''DD-MON-YYYY'')
union all
select b.bo_book_id as xt_strategy, b.bo_book_id as acct_description,case when to_char(b.pl_date,''D'') = 6 then (b.inception_pl * -1 + b.inception_premium_pl * -1) else (b.mon_pl ) end as mon_pl ,
case when to_char(b.pl_date,''D'') = 2 then (b.inception_pl * -1 + b.inception_premium_pl * -1) when to_char(b.pl_date,''D'') > 2 then (b.tue_PL) else 0 end as tue_pl, case when to_char(b.pl_date,''D'') = 3 then (b.inception_pl * -1 + b.inception_premium_pl * -1 ) when to_char(b.pl_date,''D'') > 3 then (b.wed_pl) else 0 end as wed_pl ,
case when to_char(b.pl_date,''D'') = 4 then (b.inception_pl * -1 + b.inception_premium_pl * -1 ) when to_char(b.pl_date,''D'') > 4 then (b.thu_pl ) else 0 end as thu_pl , case when to_char(b.pl_date,''D'') = 5 then (b.inception_pl *-1 + b.inception_premium_pl * -1) when to_char(b.pl_date,''D'') > 5 then (b.fri_pl) else 0 end as fri_pl ,
(b.mon_pl + b.tue_pl + b.wed_pl + b.thu_pl + b.fri_pl) + (b.inception_pl* -1 + b.inception_premium_pl * -1) as wtd_pl, case when b.wtd_premium_pl <> 0 then b.wtd_premium_pl + (b.inception_premium_pl * -1) else b.wtd_premium_pl end as wtd_premium_pl , case when b.mtd_pl <> 0 then b.mtd_pl + (b.inception_pl * -1) else b.mtd_pl end as mtd_pl ,
case when b.mtd_premium_pl <> 0 then b.mtd_premium_pl + (b.inception_premium_pl * -1) else b.mtd_premium_pl end as mtd_premium_pl, case when b.ytd_pl <> 0 then b.ytd_pl + (b.inception_pl * -1) else b.ytd_pl end as ytd_pl,
case when b.ytd_premium_pl <> 0 then b.ytd_premium_pl + (b.inception_premium_pl * -1) else b.ytd_premium_pl end as ytd_premium_pl ,
a.base_ccy as IN_STRIKECURR, a.quoted_ccy as IN_QUOTEDCUR, a.region_code as dlc_region,a.entity_acronym as dlc_entity, to_char(a.trade_id) as dtl_reference, 8 as trade_state,
case when to_char(b.pl_date,''D'') = 6 then b.pl_date + 2 else b.pl_date end as blankout_date
from tbl_trade_hist a
join tbl_pl b on a.trade_id = b.trade_id and a.version = b.trade_version
join tbl_trade_hist c on a.tradE_id = c.trade_id join tbl_pl d on c.trade_id = d.trade_id and c.version = d.trade_version and d.pl_date = (select max(e.pl_date) from tbl_pl e where c.trade_id = e.trade_id and e.pl_date <= c.amendment_date)
join tbl_bo_book f on a.bo_book_id = f.bo_book_id and f.business_area = ''OPTIONS''
where (b.bo_book_id <> d.bo_book_id or a.region_code <> c.region_code or a.entity_acronym <> c.entity_acronym or a.base_ccy <> c.base_ccy or a.quoted_ccy <> c.quoted_ccy)
and d.pl_date - b.pl_date = case when to_char(d.pl_date,''DAY'') = ''MON'' then 3 else 1 end and d.pl_date <= to_date( fv[EOD] ,''DD-MON-YYYY'') ))
group by xt_strategy,ACCT_DESCRIPTION,DLC_REGION,DLC_ENTITY';
c clob;
s varchar2(25000);
i numeric := 424;
begin
c := xml;
dbms_output.put_line('length of clob: ' || dbms_lob.getlength(c));
dbms_output.put_line('split clob at: ' || i);
dbms_output.put_line('desired substring length: ' || to_char(dbms_lob.getlength(c) - i));
s := dbms_lob.substr(c, dbms_lob.getlength(c) - i, i + 1);
dbms_output.put_line('length of substring: ' || length(s));
end;I checked for the database characterset and they are same - AL32UTF8
The result we get is
Output from MD1 database
length of clob: 10616
split clob at: 424
desired substring length: 10192
length of substring: 10192
Output from MD2 database
length of clob: 10616
split clob at: 424
desired substring length: 10192
length of substring: 8191Any idea why there is this discrepancy ?
Edited by: USER101 on Feb 19, 2010 4:24 PMThe EOF and the LF versus CR/LF could influence the count difference, yes.
Another explain could possibly be character set conversions. The BFILE I believe counts bytes, a CLOB would count "characters" - so if the source happens to contain a few multibyte characters (UTF), then the byte count would be larger than the character count.
To help you find the cause for your exact file, then I can suggest a couple of things you might do to explore the issue:
<li>Load the file into a BLOB instead of a CLOB and see what getlength() returns for the BLOB. BLOBs would also do byte counts and not try to treat the source as text.
<li>Save the CLOB back into the filesystem and compare the original file with the exported CLOB and check the differences with some filecompare tool. -
Difference between LOB segement size and DBMS_LOB.GETLENGTH
SQL> select bytes/1024/1024 from dba_segments where segment_name='SYS_LOB0000130003C00019$$';
BYTES/1024/1024
14772
SQL> select TABLE_NAME,COLUMN_NAME from dba_lobs where SEGMENT_NAME='SYS_LOB0000130003C00019$$';
TABLE_NAME
COLUMN_NAME
TBL
C1
SQL> select sum(DBMS_LOB.GETLENGTH(C1))/1024/1024 from TBL;
SUM(DBMS_LOB.GETLENGTH(C1)
30.0376911
why is there a discrepancy between the two sizes (14GB and 30MB).
Here are the storage characteristics from the TBL ddl for the C1 LOB column:
TABLESPACE TBLSPC ENABLE STORAGE IN ROW CHUNK 8192 PCTVERSION 10
NOCACHE LOGGING
STORAGE(INITIAL 1048576 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT))user10508599 wrote:
why is there a discrepancy between the two sizes (14GB and 30MB).
Here are the storage characteristics from the TBL ddl for the C1 LOB column:
TABLESPACE TBLSPC ENABLE STORAGE IN ROW CHUNK 8192 PCTVERSION 10
NOCACHE LOGGING
STORAGE(INITIAL 1048576 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT))
According to your storage parameters it only requires 14772 rows that have lob values that are stored out of row, i.e. larger than approx. 4k. For each lob segment 1M will be allocated at least, so that might a reasonable explanation.
Not sure where I had my mind when writing this, but this is certainly wrong (and no one complaining...).
You could have a lot of deleted rows in the table, or LOBs that were larger but shrinked now, or you could hit a storage allocation bug.
What is the block size of the tablespace for the LOBs?
Regards,
Randolf
Oracle related stuff blog:
http://oracle-randolf.blogspot.com/
SQLTools++ for Oracle (Open source Oracle GUI for Windows):
http://www.sqltools-plusplus.org:7676/
http://sourceforge.net/projects/sqlt-pp/
Edited by: Randolf Geist on Jun 16, 2009 7:20 AM
Corrected plain wrong statement -
Dbms_lob.getlength
Hi.
Please, I need a help using DBMS_LOB.
I have a table with a BLOB column. When I need do a INSERT or UPDATE, a trigger is executed to give no permission to insert images with size > 1Mb.
See the trigger text below:
TRIGGER TSINMETRO.HW_TRG_DDI_AFTER
BEFORE INSERT OR UPDATE
ON tsinmetro.hw_doc_digitalizados
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
declare
vblob blob;
begin
DBMS_LOB.CREATETEMPORARY(vblob,true,dbms_lob.session);
vblob:=:new.im_arquivo;
if dbms_lob.getlength(vblob) > 1000000 then
--if dbms_lob.getlength(vblob) > 1572864 then
raise_application_error(-20003,'Tamanho da imagem superior a 1 Mb');
DBMS_LOB.FREETEMPORARY(vblob);
end if;
end;
The problem is: some times is inserted images with size > 1Mb. Some times it work ok (size < 1Mb).
Some ideia about what is happening ?
Thanks.Hi,
In my application I use the following trigger code that works fine:
if dbms_lob.getlength(:new.my_blob_column) > xxx then
Did you try using directly the code:
if dbms_lob.getlength(:new.im_arquivo) > ...
instead of:
if dbms_lob.getlength(vblob) >... -
Plesae help- needing to read a blob from db into bytes[]
Hi all,
I am having a requirement to read a blob stored in the oracle table and convert it into bytes. I am loading this table (wwv_flow_files) with APEX.
The code under page 1 is as follows:
DECLARE
z number;
y varchar2(4000);
x varchar2(400);
b blob;
BEGIN
select filename,blob_content into x ,b from APEX_APPLICATION_files where name =:P1_FILE_NAME;
select length(convertBlobToBytes(b)) into z from dual;
:P1_RESULT := z;
end;
Java code is as follows:
import java.io.*;
import java.sql.Blob;
public class convertBlob {
* @param blob
* @return
public static byte[] convertBlobToBytes(Blob blob) {
if (blob==null) return null;
try {
InputStream in = blob.getBinaryStream();
int len = (int) blob.length(); //read as long
long pos = 1; //indexing starts from 1
byte[] bytes = blob.getBytes(pos, len);
in.close();
return bytes;
catch (Exception e) {
System.out.println(e.getMessage());
return null;
PL/SQL wrapper is as follows:
CREATE OR REPLACE FUNCTION convertBlobToBytes(p1 IN BLOB) RETURN LONG RAW AUTHID CURRENT_USER AS LANGUAGE JAVA NAME 'convertBlob.convertBlobToBytes(java.sql.Blob) return byte[]';
I loaded this java class and pl/sql wrapper into the database using JDEVELOPER.
But I am getting the length of the file, as twice the size.
For example, When I run the program which reads the file returns the length of the file as a byte array, the length is 819.
When I pass the same file as a blob from apex, to the java program that converts blob to bytes, the length of the file is 1638.
And hence I am getting wrong results, further in the process.
Can you please help me? Any help is appreciated.
rgds,
Suma.Hi all,
Can any of you please help me out?
rgds,
Suma. -
Converting image into byte array
Hi all,
How to convert an integer array image into byte array ?
here i have a image like this :
private static int pixelArray[] = {
0xff000000, 0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000,
0xff000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
From this one i create image like this one :
Image image = Image.createRGBImage(pixelArray, width, height, true);
Now i want to convert that pixelArray into byte array ? how to do this
additionally i want to send this byte array to servlet .
thanks in advance.Hi,
If you want to convert your int array to a byte array you should
split each integer into 4 bytes to avoid losing information. You can
rebuild your integer array later if you need to. I think this code
will work (i havent tested it):
byte[] pixel= new byte[pixelArray.length<< 2];
for (int i= pixelArray.length- 1; i>= 0; i--) {
int aux= i<< 2; // i* 4 = i<< 2
pixel[aux]= (byte) (pixelArray>> 32);
pixel[aux+ 1]= (byte) (pixelArray[i]>>> 16);
pixel[aux+ 2]= (byte) (pixelArray[i]>>> 8);
pixel[aux+ 3]= (byte) pixelArray[i];
Greets. -
How to change the image into byte and byte array into image
now i am developing one project. i want change the image into byte array and then byte array into image.
FileInputStream is = new FileInputStream(file);
byte[] result = IOUtils.toByteArray(is);
with apache common IO lib -
How do I read directly from file into byte array
I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
try
//Read File Contents into a Buffered Image
/** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
* (at least partially) a problem with non-standard colour models, which is why we set the
* destination colour model. The side effect should be standard colour model in subsequent reading.
BufferedImage bi = null;
ImageReader ir = null;
ImageInputStream stream = ImageIO.createImageInputStream(new File(path));
final Iterator i = ImageIO.getImageReaders(stream);
if (i.hasNext())
ir = (ImageReader) i.next();
ir.setInput(stream);
ImageReadParam param = ir.getDefaultReadParam();
ImageTypeSpecifier typeToUse = null;
for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
if (type.getColorModel().getColorSpace().isCS_sRGB())
typeToUse = type;
if (typeToUse != null)
param.setDestinationType(typeToUse);
bi = ir.read(0, param);
//ir.dispose(); seem to reference this in write
//stream.close();
//Write Buffered Image to Byte ArrayOutput Stream
if (bi != null)
//Convert to byte array
final ByteArrayOutputStream output = new ByteArrayOutputStream();
//Try and find corresponding writer for reader but if not possible
//we use JPG (which is always installed) instead.
final ImageWriter iw = ImageIO.getImageWriter(ir);
if (iw != null)
if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
MainWindow.logger.warning("Unable to Write Image");
else
if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
//Add to image list
final byte[] imageData = output.toByteArray();
Images.addImage(imageData);
If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.
-
Conversion of image into byte array
I have a problem in converting .png image into bytestream, if anyone can help in this pls do so.....
Hi,
To convert an Image to bytes you can use the Image.getRGB() method.
http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#getRGB(int[], int, int, int, int, int, int)
-Henrik -
Is there a way to copy a class object into a byte array? If so, how?
hi check out
http://forum.java.sun.com/thread.jspa?threadID=562268&
messageID=2766098This does not work in j2me. WriteObject does not exist, and there are no serialsation interfaces in j2me. So you'll have to do that on your own.
look here: http://java.sun.com/developer/J2METechTips/2002/tt0226.html -
How to convert a integer into bytes!!!
I am trying to pack the length of the data transamitted over a stream into 2 bytes (Each byte is a unsigned char in terms of 'C' language). When i am using the bytes in java any value greater than 127 is a negative number (I understand the very definition of 'byte' in java), my question is how to pack the length of the data the 'C' way still following Java rules??
Example :: Length of the data is 168 say!
the 2 bytes would be 0x00, 0x80 (the respective ascii values would be NULL, P) but with Java i get some thing different as we know??
byte 1 = 00 and byte 2 = -88 ( i am not sure what would be the ascii equivalent of this??)
Please help!For what it's worth:package ca.adaptor.util;
* $Id: ByteUtil.java,v 1.6 2003/03/28 18:24:47 mike Exp $
* Copyright (c) 2002 by Michael Coury
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* @author Michael Coury (mdc)
* @created Sep 20, 2002
* @version $Revision: 1.6 $, $Date: 2003/03/28 18:24:47 $
public final class ByteUtil {
private static final int __NUM_BYTES_IN_LONG_ = 8;
private static final int __NUM_BYTES_IN_INT_ = 4;
private static final int __NUM_BYTES_IN_SHORT_ = 2;
private static final int __NUM_BITS_IN_BYTE_ = 8;
private static final long __BYTE_MASK_ = 0xFF;
/** PRIVATE CONSTRUCTOR */
private ByteUtil() {}
///// ENCODE /////
* Converts a number to its binary equivalent and returns that as a byte array
public static final byte[] toBytes(final long aNum) {
final byte[] ret = new byte[__NUM_BYTES_IN_LONG_];
for(int i = 0; i < __NUM_BYTES_IN_LONG_; i++)
ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_LONG_ - 1 - i) * __NUM_BITS_IN_BYTE_));
return ret;
* Converts a number to its binary equivalent and returns that as a byte array
public static final byte[] toBytes(final int aNum) {
final byte[] ret = new byte[__NUM_BYTES_IN_INT_];
for(int i = 0; i < __NUM_BYTES_IN_INT_; i++)
ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_INT_ - 1 - i) * __NUM_BITS_IN_BYTE_));
return ret;
* Converts a number to its binary equivalent and returns that as a byte array
public static final byte[] toBytes(final short aNum) {
final byte[] ret = new byte[__NUM_BYTES_IN_SHORT_];
for(int i = 0; i < __NUM_BYTES_IN_SHORT_; i++)
ret[i] = (byte) (aNum >>> ((__NUM_BYTES_IN_SHORT_ - 1 - i) * __NUM_BITS_IN_BYTE_));
return ret;
* Converts a number to its binary equivalent and returns that as a byte array
public static final byte[] toBytes(final double aNum) {
return toBytes(Double.doubleToRawLongBits(aNum));
* Converts a number to its binary equivalent and returns that as a byte array
public static final byte[] toBytes(final float aNum) {
return toBytes(Float.floatToRawIntBits(aNum));
///// DECODE /////
* Converts a byte array representing a long back to a long
public static final long toLong(final byte[] aNum) {
try {
long ret = 0L;
for(int i = 0; i < __NUM_BYTES_IN_LONG_; i++) {
ret += ((long) aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_LONG_ - 1 - i) * __NUM_BITS_IN_BYTE_);
return ret;
catch(Exception e) {
throw new NumberFormatException("Invalid number of bytes for long. Found: " + aNum.length
+ " Required: " + __NUM_BYTES_IN_LONG_);
* Converts a byte array representing an int back to an int
public static final int toInt(final byte[] aNum) {
try {
int ret = 0;
for(int i = 0; i < __NUM_BYTES_IN_INT_; i++)
ret += (aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_INT_ - 1 - i) * __NUM_BITS_IN_BYTE_);
return ret;
catch(Exception e) {
throw new NumberFormatException("Invalid number of bytes for int. Found: " + aNum.length
+ " Required: " + __NUM_BYTES_IN_INT_);
* Converts a byte array representing a short back to a short
public static final short toShort(final byte[] aNum) {
try {
short ret = 0;
for(int i = 0; i < __NUM_BYTES_IN_SHORT_; i++)
ret += (aNum[i] & __BYTE_MASK_) << ((__NUM_BYTES_IN_SHORT_ - 1 - i) * __NUM_BITS_IN_BYTE_);
return ret;
catch(Exception e) {
throw new NumberFormatException("Invalid number of bytes for short. Found: " + aNum.length
+ " Required: " + __NUM_BYTES_IN_SHORT_);
* Converts a byte array representing a double back to a double
public static final double toDouble(final byte[] aNum) {
return Double.longBitsToDouble(toLong(aNum));
* Converts a byte array representing a float back to a float
public static final float toFloat(final byte[] aNum) {
return Float.intBitsToFloat(toInt(aNum));
///// SHIFTING /////
public static final byte shiftRightUnsigned(final byte b, final int shift) {
return (shift > __NUM_BITS_IN_BYTE_) ? 0x00 : (byte) ((b & 0xFF) >>> shift);
public static final byte shiftRight(final byte b, final int shift) {
return (byte) (b >> shift);
public static final byte shiftLeft(final byte b, final int shift) {
return (shift > __NUM_BITS_IN_BYTE_) ? 0x00 : (byte) (b << shift);
} -
How can I divide a number into bytes
I tried the icon called "split number". It didn't work for me.
Pushpa,
"split number" is certainly the VI that I would recommend you use. Keep in mind that it splits the input into two equal parts. If you input a 32-bit integer, the high 16 bits and low 16 bits correspond to the two outputs. You'll then need to split one of the previous outputs into its high and low components to access each individual byte.
You could also construct a mask, bitwise AND it with your number, and then shift the result the appropriate number of bits. However, for the sake of simplicity, I recommend that you use "Split Number."
Alan
Applications Engineer
National Instruments -
Putting integer value of 163 into byte array
I have an integer value of 163. I need to put that into a byte array. When i do, it puts it as -93. Whats wrong? and how can i put it in correctly?
Hi,
You cannot store 163 in a byte variable. In Java a byte variable will have only 8 bits and its value range will be from -128 to +127. In a byte variable you cannot store a value which is out of this range. If you try to cast an integer value which is out of this range to byte then you will get unexpected results (But you can find what the result will be).
Maybe you are looking for
-
How can I make different catalogs from the same image
How can I make different catalogs from the same image where that image has been changed in some way between the catalogs. For instance if I wanted to have a catalogs for cropped images and have 3 catalogs one for 4x6 , 5x7 and 8x10 cropping. When I t
-
HOW DO YOU ADD COMMENTARY TO A FINISHED PROJECT?
Good evening, I have a finished movie project, made with iMovie 5.02, and am wanting to add a video commentary on another button. I can create an extra button in iDVD menu, but I can't figure out how to get the movie in there. iDVD says to go to pref
-
How to pass a value to a variable at the time of scenario execution
Hi All, I need to develop a ODI scenario, wiht below requriments. I have to move data from flat file to Target DB. flat file name is not consistent, we have to pass file name at the time of scenario excution. Could any of help me how to build this OD
-
Password problems [subject edited by moderator]
Has anyone had trouble getting password changes to take? I've tried to change it 3 times, and it APPEARS to be accepted, but does not let me install software updates.
-
How do I retrieve my apps and documents from icloud
I got a new iPad after I lost one. How do I down my apps and documents, photos from iCloud